# This is a CamiTK python action
#
# Test the interaction between python and the CamiTK application using 'self' and a timer.
# This is a simple test where a counter is incremented in the tick() method called by a
# timer() that lives in Python.
# It demonstrates how state can be preserved between two timer ticks calls using internal
# variables. 
# 
# Click 'Start'/'Stop' to start/stop the timer. Note that the timer interval is slowed
# down/accelerated automatically within the tick() method.
# Note also that the parameter is set to 'read only' as a way to prove the internal
# self.counter increments properly.

import camitk
from PySide2.QtCore import QTimer

def tick(self:camitk.Action):
    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()
