#!/usr/bin/python3

import json
import sqlite3
from db import *
from globalSettings import *
from global_func import *
import cgi
import cgitb
cgitb.enable()

conn = sqlite3.connect(DBPath)
conn.text_factory = str
c = conn.cursor()


device = DeviceName


if (GUI == true):
    form = cgi.FieldStorage()
    request_Type = form.getvalue('requestType')


def read_iDac_vDac():
    
    c.execute("select name,control_sectionName,state,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from i_dac limit 40 offset 0")
    iDacData = []
    vDacData = []
    tecDacData = []
    iDacName=[]
    for col in c:
        jsonSchema = {"name": col[0],"control_sectionName":col[1], "state": col[2], "set_on_off_state": col[3], "set_current_limit": col[4],
                      "set_min_current": col[5], "set_current": col[6], "get_current": col[7], "get_hardware_id": col[8], "id": col[9]}
        iDacData.append(jsonSchema)

    c.execute("select name,state,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from v_dac limit 40 offset 0")
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "set_on_off_state": col[2], "set_current_limit": col[3],
                      "set_min_current": col[4], "set_current": col[5], "get_current": col[6], "get_hardware_id": col[7], "id": col[8]}
        vDacData.append(jsonSchema)
    
    c.execute("select name,state,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from tec_dac limit 2 offset 0")
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "set_on_off_state": col[2], "set_current_limit": col[3],
                      "set_min_current": col[4], "set_current": col[5], "get_current": col[6], "get_hardware_id": col[7], "id": col[8]}
        tecDacData.append(jsonSchema)


    # c.execute("select control_sectionName,iDacID from i_dac ORDER BY iDacID ASC")
    # for col in c:
    #     jsonSchema = {"control_sectionName": col[0], "iDacID": col[1]}
    #     iDacName.append(jsonSchema)

    dbData = {"i_dac_data": iDacData, "v_dac_data": vDacData,"tec_dac_data" : tecDacData}

    # print("llllllllllllljhhkjckj",iDacName)

    print(json.JSONEncoder().encode(dbData))

def get_idac_elementvalues(idacID):
    query = c.execute("select name,set_on_off_state,set_current,set_max_current from i_dac where id='"+str(idacID)+"'")

    res = c.fetchall()[0]
    return res

def get_vdac_elementvalues(vDacID):
    query = c.execute("select name,set_on_off_state,set_current,set_min_current,set_max_current from v_dac where id='"+str(vDacID)+"'")

    res = c.fetchall()[0]
    return res

def get_tecdac_elementvalues(tecDacID):
    query = c.execute("select name,set_on_off_state,set_current,set_min_current,set_max_current from tec_dac where id='"+str(tecDacID)+"'")

    res = c.fetchall()[0]
    return res


def update_IDac():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    idac_data = form.getvalue("idac_data")
    idac_data=json.loads(idac_data) 
    is_error = False
    error_description = None
    id_m=idac_data[0]["id"]
    db__data=[]
    #print("iDACDATA",iDacData)
    #print("idac_data",idac_data)
    c.execute("SELECT control_sectionName from i_dac where id='"+str(id_m)+"'")
    conn.commit()
    for col in c:
        jsonsc={"control_sectionName":col[0]}
        db__data.append(jsonsc)    
    for data in idac_data:
        id = data["id"]
        set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else None
        set_current = data["idac_current_value"] if "idac_current_value" in data else None
        name = data["name"] if "name" in data else None
        set_max_current = data["idac_max"] if "idac_max" in data else None
        

        c.execute("select * from i_dac where id={id}".format(id=id))

        if len(c.fetchall()) != 0:
            if CCM == true:
                # for data in idac_data:
                i_dac_name,i_dac_setOnOff,i_dac_setCurr,i_dac_max_curr = get_idac_elementvalues(id)
                set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else i_dac_setOnOff #" "
                set_current = data["idac_current_value"] if "idac_current_value" in data else i_dac_setCurr #" "
                name = data["name"] if "name" in data else i_dac_name # " "
                set_max_current = data["idac_max"] if "idac_max" in data else i_dac_max_curr # " "
                id = data["id"]
                #control_sectionName=data["control_sectionName"]
                #message = "set,element=i_dac,args=11,uuid={0},action={1},element_name={2},set_on_off_state={3},set_current={4},id={5},device={6}, set_max_current={7},control_sectionName={8}"\
                #    .format(cmd_id, cmd, name, set_on_off_state, set_current, id, device, set_max_current,control_sectionName)
                message = "set,element=i_dac,args=11,uuid={0},action={1},element_name={2},set_on_off_state={3},set_val={4},id={5},device={6}, set_max_val={7}"\
                    .format(cmd_id, cmd, name, set_on_off_state, set_current, id, device, set_max_current)
                send_ccm_msg(message)
                res1 = get_ccm_response(cmd_id)
                # print(response)
                response = json.loads(res1)
                if response["status"] == "fail":
                    is_error = True
                    error_description = response["description"]

                delete_ccm_response(cmd_id)
                #print( name, set_on_off_state, set_current, set_max_current, id)
            else:

                c.execute('''UPDATE i_dac SET name = COALESCE(?, name), set_on_off_state = COALESCE(?, set_on_off_state), set_current = COALESCE(?, set_current), set_max_current = COALESCE(?, set_max_current), edit_date = datetime() WHERE id = ? ''', [
                        name, set_on_off_state, set_current, set_max_current, id])
                conn.commit()

    control_sectionName=db__data[0]["control_sectionName"]

    if is_error:
        print(json.JSONEncoder().encode(
            {"status": "fail", "description": error_description,"name":control_sectionName}))
    else:
        print(json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Updated","name":control_sectionName}))



def update_VDac():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    vdac_data = form.getvalue("vdac_data")
    vdac_data = json.loads(vdac_data)
    is_error = False
    error_description = None
    for data in vdac_data:

        set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else None
        set_current = data["vdac_current_value"] if "vdac_current_value" in data else None
        name = data["name"] if "name" in data else None
        set_min_current = data["vdac_min"] if "vdac_min" in data else None
        set_max_current = data["vdac_max"] if "vdac_max" in data else None
        id = data["id"]

        c.execute("select * from v_dac where id={id}".format(id=id))

        if len(c.fetchall()) != 0:
            if CCM == true:
                v_dac_name,v_dac_setOnOff,v_dac_setCurr,v_dac_min_curr,v_dac_max_curr = get_vdac_elementvalues(id)
                set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else v_dac_setOnOff 
                set_current = data["vdac_current_value"] if "vdac_current_value" in data else v_dac_setCurr
                name = data["name"] if "name" in data else v_dac_name 
                set_min_current = data["vdac_min"] if "vdac_min" in data else v_dac_min_curr
                set_max_current = data["vdac_max"] if "vdac_max" in data else v_dac_max_curr
                id = data["id"]
                message = "set,element=v_dac,args=11,uuid={0},action={1},element_name={2},set_on_off_state={3},set_val={4},id={5},device={6}, set_max_val={7}, set_min_val={8}"\
                    .format(cmd_id, cmd, name, set_on_off_state, set_current, id, device, set_max_current, set_min_current)
                send_ccm_msg(message)
                res1 = get_ccm_response(cmd_id)
                response = json.loads(res1)
                # print(response)
                if response["status"] == "fail":
                    is_error = True
                    error_description = response["description"]

                delete_ccm_response(cmd_id)
            else:
                c.execute('''UPDATE v_dac SET name = COALESCE(?, name), set_on_off_state = COALESCE(?, set_on_off_state), set_current = COALESCE(?, set_current), set_min_current = COALESCE(?, set_min_current), set_max_current = COALESCE(?, set_max_current), edit_date = datetime() WHERE id = ? ''', [
                          name, set_on_off_state, set_current, set_min_current, set_max_current, id])
                conn.commit()

    if is_error:
        print(json.JSONEncoder().encode(
            {"status": "fail", "description": error_description}))
    else:
        print(json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Updated"}))

def update_TecDac():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    tecdac_data = form.getvalue("tecdac_data")
    tecdac_data = json.loads(tecdac_data)
    is_error = False
    error_description = None
    for data in tecdac_data:

        set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else None
        set_current = data["tecdac_current_value"] if "tecdac_current_value" in data else None
        name = data["name"] if "name" in data else None
        set_min_current = data["tecdac_min"] if "tecdac_min" in data else None
        set_max_current = data["tecdac_max"] if "tecdac_max" in data else None
        id = data["id"]

        c.execute("select * from tec_dac where id={id}".format(id=id))

        if len(c.fetchall()) != 0:
            if CCM == true:
                v_dac_name,v_dac_setOnOff,v_dac_setCurr,v_dac_min_curr,v_dac_max_curr = get_tecdac_elementvalues(id)
                set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else v_dac_setOnOff 
                set_current = data["tecdac_current_value"] if "tecdac_current_value" in data else v_dac_setCurr
                name = data["name"] if "name" in data else v_dac_name 
                set_min_current = data["tecdac_min"] if "tecdac_min" in data else v_dac_min_curr
                set_max_current = data["tecdac_max"] if "tecdac_max" in data else v_dac_max_curr
                id = data["id"]
                message = "set,element=tec_dac,args=11,uuid={0},action={1},element_name={2},set_on_off_state={3},set_val={4},id={5},device={6}, set_max_val={7}, set_min_val={8}"\
                    .format(cmd_id, cmd, name, set_on_off_state, set_current, id, device, set_max_current, set_min_current)
                send_ccm_msg(message)
                res1 = get_ccm_response(cmd_id)
                response = json.loads(res1)
                # print(response)
                if response["status"] == "fail":
                    is_error = True
                    error_description = response["description"]

                delete_ccm_response(cmd_id)
            else:
                c.execute('''UPDATE tec_dac SET name = COALESCE(?, name), set_on_off_state = COALESCE(?, set_on_off_state), set_current = COALESCE(?, set_current), set_min_current = COALESCE(?, set_min_current), set_max_current = COALESCE(?, set_max_current), edit_date = datetime() WHERE id = ? ''', [
                          name, set_on_off_state, set_current, set_min_current, set_max_current, id])
                conn.commit()

    if is_error:
        print(json.JSONEncoder().encode(
            {"status": "fail", "description": error_description}))
    else:
        print(json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Updated"}))


def fetchIdac():
    id=form.getvalue('va')
    # id=1
    data_to_send=form.getvalue("data_to_send")
    dbda=[]
    c.execute("SELECT * from i_dac where id='"+str(id)+"'")
    conn.commit()
    for col in c:
        jsonschem={"id":col[0],"name":col[1],'control_sectionName':col[2],"state":col[3],"set_on_off_state":col[4],"get_on_off_state":col[5],"set_max_current":col[6],"set_min_current":col[7],"set_current":col[8],"get_current":col[9]}
        dbda.append(jsonschem)

    print(json.JSONEncoder().encode(dbda))

def fetchVdac():
    id=form.getvalue('va')
    # id=1
    data_to_send=form.getvalue("data_to_send")
    dbda=[]
    c.execute("SELECT * from v_dac where id='"+str(id)+"'")
    conn.commit()
    for col in c:
        jsonschem={"id":col[0],"name":col[1],'control_sectionName':col[2],"state":col[3],"set_on_off_state":col[4],"get_on_off_state":col[5],"set_max_current":col[6],"set_min_current":col[7],"set_current":col[8],"get_current":col[9]}
        dbda.append(jsonschem)

    print(json.JSONEncoder().encode(dbda))

print("Content-type:/text/json\r\n\r\n")


if(request_Type == 'updateIdac'):
    update_IDac()
if(request_Type == 'updateVdac'):
    update_VDac()
if(request_Type == 'updateTecdac'):
    update_TecDac()
if(request_Type == 'fetchIdac'):
    fetchIdac()
if(request_Type == 'fetchVdac'):
    fetchVdac()
if(request_Type == 'read_iDac_vDac'):
    read_iDac_vDac()



c.close()
conn.close()
