1#!/router/bin/python
2from __future__ import print_function
3import threading
4import sys
5import time
6import outer_packages
7import termstyle
8import progressbar
9
10
11class ProgressThread(threading.Thread):
12    def __init__(self, notifyMessage = None):
13        super(ProgressThread, self).__init__()
14        self.stoprequest = threading.Event()
15        self.notifyMessage = notifyMessage
16
17    def run(self):
18        if self.notifyMessage is not None:
19            print(self.notifyMessage, end=' ')
20
21        while not self.stoprequest.is_set():
22            print("\b.", end=' ')
23            sys.stdout.flush()
24            time.sleep(5)
25
26    def join(self, timeout=None):
27        if self.notifyMessage is not None:
28            print(termstyle.green("Done!\n"), end=' ')
29        self.stoprequest.set()
30        super(ProgressThread, self).join(timeout)
31
32
33class TimedProgressBar(threading.Thread):
34    def __init__(self, time_in_secs):
35        super(TimedProgressBar, self).__init__()
36        self.stoprequest    = threading.Event()
37        self.stopFlag       = False
38        self.time_in_secs   = time_in_secs + 15 # 80 # taking 15 seconds extra
39        widgets             = ['Running TRex: ', progressbar.Percentage(), ' ',
40                   progressbar.Bar(marker='>',left='[',right=']'),
41                   ' ', progressbar.ETA()]
42        self.pbar           = progressbar.ProgressBar(widgets=widgets, maxval=self.time_in_secs*2)
43
44
45    def run (self):
46        # global g_stop
47        print()
48        self.pbar.start()
49
50        try:
51            for i in range(0, self.time_in_secs*2 + 1):
52                if (self.stopFlag == True):
53                    break
54                time.sleep(0.5)
55                self.pbar.update(i)
56            # self.pbar.finish()
57
58        except KeyboardInterrupt:
59            # self.pbar.finish()
60            print("\nInterrupted by user!!")
61            self.join()
62        finally:
63            print()
64
65    def join(self, isPlannedStop = True, timeout=None):
66        if isPlannedStop:
67            self.pbar.update(self.time_in_secs*2)
68            self.stopFlag = True
69        else:
70            self.stopFlag = True # Stop the progress bar in its current location
71        self.stoprequest.set()
72        super(TimedProgressBar, self).join(timeout)
73
74
75def timedProgressBar(time_in_secs):
76    widgets = ['Running TRex: ', progressbar.Percentage(), ' ',
77                   Bar(marker='>',left='[',right=']'),
78                   ' ', progressbar.ETA()]
79    pbar = progressbar.ProgressBar(widgets=widgets, maxval=time_in_secs*2)
80    pbar.start()
81    for i in range(0, time_in_secs*2 + 1):
82        time.sleep(0.5)
83        pbar.update(i)
84    pbar.finish()
85    print()
86
87
88