import numpy as np
import json
from aplant import APlant
from math import sqrt

class Mass(APlant):
	def __init__(self, params):
		print(json.dumps({'Mass': params}, indent=4, sort_keys=True))
		self.dt = params['dt']
		self.alpha = 1.0

		self.e = 0
		self.x = 0
		self.gain = 0.999

		self.C = params['C']
		self.M = params['M']
		self.L = params['L']
		self.Td = params['Td']
		self.kn = params['kn']
		self.theta_amb = params['theta_amb']

		self.theta = 0
		self.P = 0

		self.alpha = self.dt/1

		self.Nd = int(self.Td/self.dt)
		self.delay = np.zeros((self.Nd, 1))
		self.ri = 0
		self.wi = 0

	def activate(self, enable):
		pass

	def process(self):
		if self.ri >= self.delay.size:
			self.ri = 0
		P = self.delay[self.ri][0]
		self.ri += 1

		self.e = self.e*(1 - ((self.L*self.theta)*self.dt)/(self.M*self.C))
		self.x = (1-self.alpha)*self.x + self.gain*self.alpha*P
		self.e += self.x
		self.theta = self.e/(self.M*self.C)

	def setPower(self, power_w):
		k = int(power_w / 100 +0.5)
		P = k * 100
		if self.wi >= self.delay.size:
			self.wi = 0
		self.delay[self.wi] = P
		self.wi += 1
		self.P = P

	def getPower(self):
		return self.P
	
	def getTemperature(self):
		return round(self.theta + self.theta_amb + self.kn*np.random.normal(0,1)/sqrt(12.0), 1)
