1/*
2Copyright (c) 2014 VMware, Inc. All Rights Reserved.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package progress
18
19type scaledReport struct {
20	Report
21	n int
22	i int
23}
24
25func (r scaledReport) Percentage() float32 {
26	b := 100 * float32(r.i) / float32(r.n)
27	return b + (r.Report.Percentage() / float32(r.n))
28}
29
30type scaleOne struct {
31	s Sinker
32	n int
33	i int
34}
35
36func (s scaleOne) Sink() chan<- Report {
37	upstream := make(chan Report)
38	downstream := s.s.Sink()
39	go s.loop(upstream, downstream)
40	return upstream
41}
42
43func (s scaleOne) loop(upstream <-chan Report, downstream chan<- Report) {
44	defer close(downstream)
45
46	for r := range upstream {
47		downstream <- scaledReport{
48			Report: r,
49			n:      s.n,
50			i:      s.i,
51		}
52	}
53}
54
55type scaleMany struct {
56	s Sinker
57	n int
58	i int
59}
60
61func Scale(s Sinker, n int) Sinker {
62	return &scaleMany{
63		s: s,
64		n: n,
65	}
66}
67
68func (s *scaleMany) Sink() chan<- Report {
69	if s.i == s.n {
70		s.n++
71	}
72
73	ch := scaleOne{s: s.s, n: s.n, i: s.i}.Sink()
74	s.i++
75	return ch
76}
77