# This is a CamiTK python action
import camitk
from PySideX.QtCore import QTimer

def tick(self):
    self.counter += 1
    camitk.info(f"counter: {self.counter}")

    # Backup state C++ memory is required as self.counter has changed in a 
    # method that is not called directly from C++ (init, process, targetDefined, parameterChanged),
    # i.e., a function called from python by python.
    # This is required to ensure the C++/python values are properly synchronized
    self.saveState()
    
    # call to set ParameterValue must be done _after_ saveState()
    self.setParameterValue("Counter", self.counter)
    self.timer.setInterval(int(1000.0 / float(self.counter%10 + 1)))

    # update action (default) widget
    self.updateWidget()

def init(self:camitk.Action):
    self.timer = None
    self.setApplyButtonText("Start")

def process(self:camitk.Action):
    self.counter = self.getParameterValue("Counter")

    if not self.timer:
        self.timer = QTimer()
        connected = self.timer.timeout.connect(lambda: tick(self))     

    if not self.timer.isActive():
        self.setApplyButtonText("Stop")
        self.timer.start(1000)
    else:
        self.setApplyButtonText("Restart")
        self.timer.stop()
