import asyncio
from tasks import ATask
from ws.message import MsgIo
from utils.value import ChangedFloat
from components import APid


class TcTask(ATask):
	def __init__(self, tc: APid, interval, msg_handler: MsgIo):
		ATask.__init__(self, interval)

		self.tc = tc
		self.msg_handler = msg_handler
		msg_handler.set_recv_handler(self.recv)

	def on_state_changed(self, value):
		print ("State change to {}".format(value))
		asyncio.create_task(self.send({'State': str(value)}))

	def on_temp_soll_changed(self, value):
		print ("Temp soll change to {}".format(value))
		asyncio.create_task(self.send({'Soll': {'Temp': value}}))

	def on_rate_soll_curr_changed(self, value):
		print ("Rate soll change to {}".format(value))
		asyncio.create_task(self.send({'Soll': {'Rate': {'Current': value}}}))

	def on_rate_soll_set_changed(self, value):
		print ("Rate soll change to {}".format(value))
		asyncio.create_task(self.send({'Soll': {'Rate': {'Set': value}}}))

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

	def on_rate_ist_changed(self, value):
		asyncio.create_task(self.send({'Ist': {'Rate': value}}))

	async def recv(self, msg):
		print(msg)
		for key in msg.keys():
			if 'Soll' in key:
				submsg = msg['Soll']
				for subkey in submsg.keys():
					if 'Temp' in subkey:
						self.tc.set_theta_soll(submsg['Temp'])
					if 'Rate' in subkey:
						self.tc.set_heatrate_soll(submsg['Rate'])

	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.tc.set_on_changed('state', self.on_state_changed)
		self.tc.set_on_changed('theta_ist', ChangedFloat(self.on_temp_ist_changed, prec=1).set)
		self.tc.set_on_changed('heatrate_ist', ChangedFloat(self.on_rate_ist_changed, prec=1).set)
		self.tc.set_on_changed('theta_soll_set', ChangedFloat(self.on_temp_soll_changed, prec=1).set)
		self.tc.set_on_changed('heatrate_soll', ChangedFloat(self.on_rate_soll_curr_changed, prec=1).set)
		self.tc.set_on_changed('heatrate_soll_set', ChangedFloat(self.on_rate_soll_set_changed, prec=1).set)

		self.tc.set_theta_soll(20.0)
		self.tc.set_heatrate_soll(1.0)

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

