# @Author: Stijn Van Hulle <stijnvanhulle>
# @Date:   2016-11-28T13:51:38+01:00
# @Email:  me@stijnvanhulle.be
# @Last modified by:   stijnvanhulle
# @Last modified time: 2016-12-20T12:51:07+01:00
# @License: stijnvanhulle.be



#!/usr/bin/env python

import time
import datetime
import math
import sys
import json
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import lib.faceDetection as faceDetection
import lib.levelCalculation as levelCalculation


MQTT_BROKER="localhost"
client = mqtt.Client()

#classes

def on_connect(client, userdata, rc):
	print("Connected to MQTT-broker on " + MQTT_BROKER )
	client.subscribe("online")
	client.subscribe("message")
	client.subscribe("detection_find")
	client.subscribe("detection_found")

	client.subscribe("recalculate_start")
	client.subscribe("recalculate_done")

def on_message(client, userdata, msg):
	try:
		parsed_json=json.loads(convertJson(msg.payload))


		if msg.topic=="detection_find":	
			print(parsed_json)
			_image1 =parsed_json['image1']
			_image2 =parsed_json['image2']
			_read=parsed_json['read']
			if _read:
				if _image1 is not None  and _image2 is not None:
					percent=faceDetection.getDifference(_image1,_image2)
					print('Detection:' + str(percent))
					client.publish("detection_found", makeJsonObject_detection(percent,_image1,_image2,_read))	

		if msg.topic=="recalculate_start":
			print(parsed_json)
			_data =parsed_json['data']
			_file=parsed_json['file']
			if _data is not None:
				calcObj=levelCalculation.calculate(_data,_file)
				print('CalculatedOBJ:' + str(calcObj))
				client.publish("recalculate_done", makeJsonObject_levelCalculate(calcObj['data'],calcObj['score']))		
	except Exception as error:
			print('Error:',error)




def convertJson(data):
	data=data.decode()

	if data.startswith("'") and data.endswith("'"):
		data = data[1:-1]
		print(data)
	return data
def makeJsonOnlineObject(device=''):
	item=json.dumps({"device":device})
	return str(item)

def init():
	client.on_connect = on_connect
	client.on_message = on_message
	client.connect_async(MQTT_BROKER, 1883, 60)
	client.loop_start()
	time.sleep(0.2)
	client.publish("online", makeJsonOnlineObject('FaceDetection'))

def makeJsonObject(value=None,port=None,type=None,read=False):
	item=json.dumps({"port":port, "type":type,"value":value,"read":read})
	return str(item)

def makeJsonObject_detection(value=None,image1=None,image2=None,read=False):
	item=json.dumps({"value":value, "image1":image1,"image2":image2, "read":read})
	return str(item)
	
def makeJsonObject_levelCalculate(data=None,score=0):
	item=json.dumps({"data":data,"score":score})
	return str(item)


def main():
	init()

	while True:
		time.sleep(0.1)
		data = input("Code:")
		if data is not None:
			try:
				if data=='exit':
					exit()
					sys.exit(0)
				else:
					parsed_json=json.loads(convertJson(msg.payload))
					_type =parsed_json['type']
					_port=parsed_json['port']
					_read=parsed_json['read']

					if _type is not None and _port is not None and _read is not None:
						item=str(json.dumps(parsed_json))
						print(item)
						#client.publish("message",item)
						client.publish("detection",item)
					else:
						throw('Not correct data')
			except Exception as error:
				print('Error:',error)


if __name__ == '__main__':

	try:
		if len(sys.argv)>1:
			MQTT_BROKER=sys.argv[1]
		else:
			input_text = input("Ip of MQTT-broker: ")
			if input_text:
				MQTT_BROKER=input_text

		#executor = ProcessPoolExecutor(2)
		#loop = trollius.get_event_loop()
		#_main = trollius.async(loop.run_in_executor(executor, main))
		main()
	except (TypeError) as ex:
		error="Error: " + str(ex)
		#print(error)
	except (KeyboardInterrupt):
		exit()
		print("\nIOT is afgesloten\n")
		sys.exit(0)
	except (SystemExit):
		print("\nIOT is geforceert afgelosten\n")

[((24, 9, 24, 22), 'paho.mqtt.client.Client', 'mqtt.Client', ({}, {}), '()', True, 'import paho.mqtt.client as mqtt\n'), ((76, 6, 76, 35), 'json.dumps', 'json.dumps', ({(76, 17, 76, 34): "{'device': device}"}, {}), "({'device': device})", False, 'import json\n'), ((84, 1, 84, 16), 'time.sleep', 'time.sleep', ({(84, 12, 84, 15): '(0.2)'}, {}), '(0.2)', False, 'import time\n'), ((88, 6, 88, 70), 'json.dumps', 'json.dumps', ({(88, 17, 88, 69): "{'port': port, 'type': type, 'value': value, 'read': read}"}, {}), "({'port': port, 'type': type, 'value': value, 'read': read})", False, 'import json\n'), ((92, 6, 92, 79), 'json.dumps', 'json.dumps', ({(92, 17, 92, 78): "{'value': value, 'image1': image1, 'image2': image2, 'read': read}"}, {}), "({'value': value, 'image1': image1, 'image2': image2, 'read': read})", False, 'import json\n'), ((96, 6, 96, 45), 'json.dumps', 'json.dumps', ({(96, 17, 96, 44): "{'data': data, 'score': score}"}, {}), "({'data': data, 'score': score})", False, 'import json\n'), ((104, 2, 104, 17), 'time.sleep', 'time.sleep', ({(104, 13, 104, 16): '(0.1)'}, {}), '(0.1)', False, 'import time\n'), ((148, 2, 148, 13), 'sys.exit', 'sys.exit', ({(148, 11, 148, 12): '(0)'}, {}), '(0)', False, 'import sys\n'), ((59, 12, 59, 51), 'lib.levelCalculation.calculate', 'levelCalculation.calculate', ({(59, 39, 59, 44): '_data', (59, 45, 59, 50): '_file'}, {}), '(_data, _file)', True, 'import lib.levelCalculation as levelCalculation\n'), ((50, 13, 50, 57), 'lib.faceDetection.getDifference', 'faceDetection.getDifference', ({(50, 41, 50, 48): '_image1', (50, 49, 50, 56): '_image2'}, {}), '(_image1, _image2)', True, 'import lib.faceDetection as faceDetection\n'), ((110, 5, 110, 16), 'sys.exit', 'sys.exit', ({(110, 14, 110, 15): '(0)'}, {}), '(0)', False, 'import sys\n'), ((118, 15, 118, 38), 'json.dumps', 'json.dumps', ({(118, 26, 118, 37): 'parsed_json'}, {}), '(parsed_json)', False, 'import json\n')]