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

	def on_state_changed(self, value):
		asyncio.create_task(self.send({'State': str(value)}))

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

	def on_rate_soll_curr_changed(self, value):
		asyncio.create_task(self.send({'Soll': {'Rate': {'Current': value}}}))

	def on_rate_soll_set_changed(self, 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}}))

	def on_enabled_changed(self, value):
		asyncio.create_task(self.send({'Enabled': value}))

	async def recv(self, msg):
		if 'Soll' in msg:
			submsg = msg['Soll']
			if 'Temp' in submsg:
				self.tc.set_theta_soll(submsg['Temp'])
			if 'Rate' in submsg:
				self.tc.set_heatrate_soll(submsg['Rate'])
		if 'Enable' in msg:
			self.tc.set_enabled(bool(msg['Enable']))

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

	async def on_process(self):
		self.tc.set_theta_soll(20.0)
		self.tc.set_heatrate_soll(1.0)
		await self.send({'Enabled': self.tc.enabled})

		while True:
			# Stays inert until set_params() (and, for a model-based
			# controller like Smith, its model's plant params/ambient too
			# - see components/pid/temp_controller_smith.py's
			# is_configured()) has actually been supplied - process()
			# would otherwise raise.
			if self.tc.is_configured():
				self.tc.process()
			else:
				# Smith's model plant params only ever arrive from a Sud's
				# doc (see brewpi.py), so right after server start - before
				# any Sud has ever loaded - is_configured() stays False and
				# process() never runs. Without this, theta_ist/
				# heatrate_ist/heatrate_soll (and thus the 'Ist'/'Soll'
				# messages below) would stay frozen at their __init__
				# defaults forever, leaving the GUI's Ist Temp/Rate and
				# Soll Rate displays blank on connect. Mirror the raw
				# sensor reading straight through instead - there's no
				# controller output yet to report a real rate for.
				self.tc.theta_ist = self.tc.get_theta_ist_set()
				self.tc.heatrate_ist = 0.0
				self.tc.heatrate_soll = 0.0
			await asyncio.sleep(self.interval)

