#!/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,state,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from i_dac")
    iDacData = []
    vDacData = []
    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]}
        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")
    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)
    dbData = {"i_dac_data": iDacData, "v_dac_data": vDacData}

    print(json.JSONEncoder().encode(dbData))
    c.close()
    conn.close()


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
    for data in idac_data:

        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
        id = data["id"]

        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:
                set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else " "
                set_current = data["idac_current_value"] if "idac_current_value" in data else " "
                name = data["name"] if "name" in data else " "
                set_max_current = data["idac_max"] if "idac_max" in data else " "
                id = data["id"]
                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}"\
                    .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)
            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()

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

    c.close()
    conn.close()


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:
                set_on_off_state = data["turnOnOffState"] if "turnOnOffState" in data else " "
                set_current = data["vdac_current_value"] if "vdac_current_value" in data else " "
                name = data["name"] if "name" in data else " "
                set_min_current = data["vdac_min"] if "vdac_min" in data else " "
                set_max_current = data["vdac_max"] if "vdac_max" in data else " "
                id = data["id"]
                message = "set,element=v_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}, set_min_current={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"}))

    c.close()
    conn.close()


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


if(request_Type == 'updateIdac'):
    update_IDac()
if(request_Type == 'updateVdac'):
    update_VDac()
if(request_Type == 'read_iDac_vDac'):
    read_iDac_vDac()
