#!/usr/bin/python3

import cgi, cgitb
import json
import subprocess
import sqlite3
from datetime import datetime
cgitb.enable()
from globalSettings import *
from global_func import *
import ast


device=DeviceName

form = cgi.FieldStorage()
request_Type = form.getvalue('requestType')


def tecTest():
    db_open = False
    try:
        conn = sqlite3.connect(DBPath)
        conn.text_factory = str
        c = conn.cursor()
        db_open = True

        cmd = "TEC_Test"
        cmd_id = get_ccm_command_id()

        message = "set,element=TEC_Test,args=12,uuid={0},action={1},device={2}".\
        format(cmd_id,cmd,device)
        #send_ccm_msg(message)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        delete_ccm_response(cmd_id)
        
        response = json.loads(response)
        if 'status' in response and response['status'] == 'fail':
            print(json.dumps(response))

        else:

            result = ast.literal_eval(response["result"])
            pretty_updates = {}

            if response["status"] == "success" and len(result) > 2:
                updates = result[2] or {}
                
                c.execute("UPDATE tec SET state = 0")
                c.execute("UPDATE i_drive SET state = 0")

                with open(TEC_LOG, "w") as f:
                    f.write(f"TEC Error Log - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                    f.write("=" * 60 + "\n\n")
                    f.write("TEC Status Codes:\n")
                    f.write("1 = TEC Not Connected\n")
                    f.write("2 = Laser Not Connected\n")
                    f.write("0 = All Good\n\n")
                    f.write(result[1] + "\n\n")

                if updates:
                    for key , value in updates.items():
                        tec_status = value.get("tec", 0)
                        laser_status = value.get("laser", 0)

                        c.execute("update tec set state = ? where id = ?",(tec_status,key))
                        c.execute("update i_drive set state = ? where id = ?",(laser_status,key))

                        with open(TEC_LOG, "a") as f:
                            f.write(f"{key} - Status : {'TEC Not Connected' if tec_status == 1 else 'TEC Connected'} | {'Laser Not Connected' if laser_status == 2 else 'Laser Connected'}\n")

                        pretty_updates[key] = {
                            "tec_text": "Connected" if value.get("tec", 0) == 0 else "Disconnected",
                            "laser_text": "Connected" if value.get("laser", 0) == 0 else "Disconnected",
                            "tec": value.get("tec", 0),
                            "laser": value.get("laser", 0)
                        }
                else:
                    with open(TEC_LOG, "a") as f:
                        f.write("No errors found. All TEC and Laser records are healthy.\n")
                print(json.JSONEncoder().encode({ "status" : "success" , "description" : "TEC Current test completed !!", "result" : pretty_updates }))
            else:
                print(json.dumps(response))

            conn.commit()

        if db_open:
            c.close()
            conn.close()
            db_open = False
        
    except Exception as e:
        if db_open:
            c.close()
            conn.close()
            db_open = False
        print(json.JSONEncoder().encode({ "status" : "fail" , "description" : str(e) }))


print("Content-Type:text/html\r\n\r\n")
if request_Type == "tecTest":
    tecTest()
else:
    print(json.JSONEncoder().encode({ "status" : "fail" , "message" : "Invalid Request" }))