from java.net.http import HttpClient;
from java.net.http import WebSocket;
from java.net import URI
import json


class listener(WebSocket.Listener):
    
	def __init__(self,whid):
		self.whid = whid
		self.alarms = {}
		self.tag_provider ="[%s_SCADA_TAG_PROVIDER]" % (self.whid)
		self.logger = system.util.getLogger("%s-Web-Socket-Listener" % (whid))

	def onOpen(self, websocket):
		on_open_subscribe = json.dumps({"action":"subscribe",
		                                "parameters":{"siteId":self.whid}}
		                                )
		websocket.sendText(on_open_subscribe, True)
		logger = system.util.getLogger("Web-Socket-OnOpen")
		logger.info("message sent =" +  str(on_open_subscribe))


	def onText(self, websocket, data, last):
	#   
		alarm_message = None
		
		try:
			json_data = json.loads(str(data))
			alarm_message = json_data.get("type")
		
		except ValueError as e:
			self.logger.info("Unable to load Json object, malformed message")
			
		
		if alarm_message == "alarm":
			
			
			id = json_data.get("sourceId")
			state = json_data.get("state")
			
			if state == 1:
				removed_value = self.alarms.pop(id, "No key found")
			
			else:
				self.alarms[id]= json_data
				self.logger.info("this has been triggered")
				self.logger.info("State is equal to " + str(state))
			system.tag.writeBlocking([self.tag_provider + "System/aws_data"],
			                        [system.util.jsonEncode(self.alarms)]
			                        )
			self.logger.info("Data written to tag : " + str(self.alarms))
		
		self.logger.info("Response from server: " + str(data))
		websocket.request(1)
#		return None
	
	def onClose(self, websocket, error):
#		print("Socket is closed")
#  		logger = system.util.getLogger("OnClose-Web-Socket")
		self.logger.info("Onclose method closed " + str(error))
	
	def onError(self, websocket, error):
#	    logger = system.util.getLogger("OnError-Web-Socket")
	    self.logger.info("OnError method closed " + str(error))

