#!/usr/bin/env python3
from datetime import datetime
from flask import Flask, request, render_template

data_log = []
log_file="data_log.tsv"

app = Flask(__name__)

#příklad předání dat serveru
#127.0.0.1:5000/Temperature_control_and_monitoring_system/give_data?Tamb=2059&TinUp=2548&TinDwn=2480&Tset=2900&Hup=50&Hdwn=50&Iheat=0&Icool=159&Doors=1&Tscale=100&Iscale=1000
@app.route("/Temperature_control_and_monitoring_system/give_data")
def main():
	now=((datetime.now()).strftime("%Y/%m/%d\t%H:%M:%S"))
	Temp_scale=float(request.args.get('Tscale'))
	I_scale=float(request.args.get('Iscale'))
	Temp_amb=str(float(request.args.get('Tamb'))/Temp_scale)
	Temp_in_up=str(float(request.args.get('TinUp'))/Temp_scale)
	Temp_in_dwn=str(float(request.args.get('TinDwn'))/Temp_scale)
	Temp_set=str(float(request.args.get('Tset'))/Temp_scale)
	Hys_up=str(float(request.args.get('Hup'))/Temp_scale)
	Hys_dwn=str(float(request.args.get('Hdwn'))/Temp_scale)
	I_heater=str(float(request.args.get('Iheat'))/I_scale)
	I_cooler=str(float(request.args.get('Icool'))/I_scale)
	Doors_open=str(int(not(int(request.args.get('Doors')))))
	

	log=open(log_file, "at")
	log.close()
	log=open(log_file, "rt")
	if len(log.read())==0:
		log.close()
		log=open(log_file, "wt")
		log.write("Y/m/d\th:m:s\tTemp_amb\tTemp_in_up\tTemp_in_dwn\tTemp_set\tHys_up\tHys_dwn\tI_heater\tI_cooler\tDoors_open\n")
	log.close()
	
	log=open(log_file, "at")
	log.write(f"{now}\t{Temp_amb}\t{Temp_in_up}\t{Temp_in_dwn}\t{Temp_set}\t{Hys_up}\t{Hys_dwn}\t{I_heater}\t{I_cooler}\t{Doors_open}\n")

	year=((datetime.now()).strftime("%Y"))
	month=((datetime.now()).strftime("%m"))
	day=((datetime.now()).strftime("%d"))
	hour=((datetime.now()).strftime("%H"))
	minute=((datetime.now()).strftime("%M"))
	second=((datetime.now()).strftime("%S"))

	data_log.append((Temp_amb, Temp_in_up, Temp_in_dwn, Temp_set, str(float(Hys_up)+float(Temp_set)), str(float(Temp_set)-float(Hys_dwn)), I_heater, I_cooler, Doors_open, year, month, day, hour, minute, second))



	log.close()
	return f"Data přijata {now}"


@app.route("/Temperature_control_and_monitoring_system")
def Chart():

	kwargs = {"data_log": data_log, "count": len(data_log)}

	return render_template("tcms.html", **kwargs)

if __name__ == "__main__":
	app.run(host='0.0.0.0')
