import asyncio
from tasks import ATask
from ws.message import MsgIo
from components import AStirrer
from utils.value import ChangedInteger


class StirrerTask(ATask):
	def __init__(self, stirrer_device: AStirrer, interval, msg_handler: MsgIo):
		ATask.__init__(self, interval)
		self.msg_handler = msg_handler
		msg_handler.set_recv_handler(self.recv)
		self.device = stirrer_device

	def on_speed_changed(self, value):
		asyncio.create_task(self.send({'Speed': value}))

	def on_dutycycle_changed(self, value):
		asyncio.create_task(self.send({'DutyCycle': value}))

	def on_cycletime_changed(self, value):
		asyncio.create_task(self.send({'CycleTime': value}))

	async def recv(self, data):
		for pair in data.items():
			if 'Speed' in pair[0]:
				self.device.set_speed(pair[1])

	async def send(self, data):
		await self.msg_handler.send(data)

	async def on_process(self):
		print("{}: Started with interval {} s".format(self.msg_handler.get_key(), self.interval))
		self.device.set_on_changed("speed", self.on_speed_changed)
		self.device.set_on_changed("dutyCycle", self.on_dutycycle_changed)
		self.device.set_on_changed("cycleTime", self.on_cycletime_changed)

		self.device.set_speed(50.0)
		self.device.set_cycle_time(10.0)
		self.device.set_duty_cycle(1.0)

		with self.device.open():
			while True:
				self.device.process()
				await asyncio.sleep(self.interval)
