import vts


class Mgr_Timers:
    obj_count = 0
    Timers = {}

    def __init__(self):
        if Mgr_Timers.obj_count != 0:
            raise Exception('Timer Mgr: there can be only one')
        Mgr_Timers.obj_count += 1

    class Py_Timer:
        def __init__(self, period, repeat, cbs = None):
            self.period = period
            self.timer = vts.Timer(period, repeat)
            self.Callbacks = {}
            if cbs:
                for idx, func in enumerate(cbs):
                    self.Callbacks["{}".format(idx)] = func
            self.timer.set_callback(self.Callback)

        def Callback(self):
            for func in self.Callbacks:
                self.Callbacks[func](self.period)

        def add_cb(self, key, func):
            self.Callbacks[key] = func

        def rm_cb(self, key):
            if self.Callbacks[key]:
                del self.Callbacks[key]
            if not self.Callbacks:
                self.destroy()

        def destroy(self):
            self.timer.set_callback(None)
            self.timer.destroy()
            self.timer = None
            del Mgr_Timers.Timers[self.period]

    @classmethod
    def add_clock(self, period = None, frequncy = None):
        if period and not frequncy:
            if not period in self.Timers:
                self.Timers[period] = self.Py_Timer(period, True)


        elif frequncy and not period:   # DOES NOT WORK
            self.Timers[period] = self.Py_Timer(1/frequncy, True) # 1/frequncy ???
        else:
            # rasie error (one or the other)
            print("Only period or frequncy please")


    @classmethod
    def add_timer(self, period, cbs):
        self.Timers[key] = Py_timer( period, False, cbs = cbs)
