# This is a CamiTK python action
#
# Test the interaction between python and the CamiTK application using a parameter 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 the action
# parameters. 
# Click 'Start'/'Stop' to start/stop the timer. 
# Note that the timer interval is slowed down/accelerated automatically within the tick() method.

import camitk
from PySide2.QtCore import QTimer
import sys

def tick(self:camitk.Action):
    counter = self.getParameterValue("Counter")
    print(f"test_parameter_interaction_timer tick {counter} (this is stderr)", file=sys.stderr) # first print is on stderr

    counter += 1
    self.setParameterValue("Counter", counter)

    self.timer.setInterval(int(1000.0 / float(counter%10 + 1)))
    self.updateWidget()
    print(f"test_parameter_interaction_timer tick {counter} (this is stdout)") # second print on stdout
    
def init(self:camitk.Action):
    print("test_parameter_interaction_timer init", file=sys.stderr)
    self.timer = None
    self.setApplyButtonText("Start")

def process(self:camitk.Action):
    self.counter = self.getParameterValue("Counter")
    print(f"test_parameter_interaction_timer process {self.counter}", file=sys.stderr)

    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()
