import asyncio
from tasks import ATask
from ws.message import MsgIo
from utils.value import ChangedInteger, ChangedFloat
from components.plant import APlant


class PotTask(ATask):
	def __init__(self, pot: APlant, interval, msg_handler: MsgIo):
		ATask.__init__(self, interval)

		self.msg_handler = msg_handler
		msg_handler.set_recv_handler(self.recv)
		self.plant = pot

	def on_changed_power(self, value):
		asyncio.create_task(self.send({'Power': value}))

	def on_changed_temp(self, value):
		asyncio.create_task(self.send({'Temp': value}))

	async def recv(self, data):
		pass

	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.plant.set_on_changed('power_actual', ChangedInteger(self.on_changed_power).set)
		self.plant.set_on_changed('temp', ChangedFloat(self.on_changed_temp, prec=1).set)

		while True:
			self.plant.process()
			await asyncio.sleep(self.interval)


