#!/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()

true = 0
false = 1

GUI = false
CCM = true

device = DeviceName

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

else:
    print("1.Create Demux point lut")
    print("2.Update Demux point lut")
    print("3.Delete Demux point lut")
    print("4.Read Demux point lut")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_DemuxPointLut'
    elif choice == 2:
        request_Type = 'update_DemuxPointLut'
    elif choice == 3:
        request_Type = 'delete_DemuxPointLut'
    elif choice == 4:
        request_Type = 'read_DemuxPointLut'
    else:
        print("Enter Valid choice")
    print("Reques_Type="+str(request_Type))


def form_getvalue(val):
    if val == "demux_id":
        demux_id = str(input("Enter demuxMap_id of the Demux point lut: "))
        return demux_id
    if val == "tone":
        tone = str(input("Enter tone of the Demux point lut: "))
        return tone
    if val == "rf_amp_id":
        rf_amp_id = str(input("Enter rf_amp_id:"))
        return rf_amp_id
    if val == "fsr_high":
        fsr_high = str(input("Enter fsr_high of the Demux point lut: "))
        return fsr_high
    if val == "fsr_low":
        fsr_low = str((input("Enter fsr_low of the Demux point lut: ")))
        return fsr_low
    if val == "comb_wav":
        comb_wav = str(input("Enter Demux point lut comb_wav NUmber: "))
        return comb_wav
    if val == "TEC_id":
        TEC_id = str(input("Enter TEC_id:"))
        return TEC_id
    if val == "def_temperature":
        def_temperature = str(
            input("Enter def_temperature of the Demux point lut: "))
        return def_temperature
    if val == "i_drive_id":
        i_drive_id = str((input("Enter i_drive_id of the Demux point lut: ")))
        return i_drive_id
    if val == "set_current":
        set_current = str(input("Enter Demux point lut set_current NUmber: "))
        return set_current
    if val == "uuid_cur_set":
        uuid_cur_set = str(
            input("Enter Demux point lut uuid_cur_set NUmber: "))
        return uuid_cur_set
    if val == "id":
        Id = int(input("Enter Id of the Demux point lut: "))
        return Id


def create_DemuxPointLut():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        demux_id = form.getvalue("demux_id")
        tone = form.getvalue("tone")
        rf_amp_id = form.getvalue("rf_amp_id")
        fsr_high = form.getvalue("fsr_high")
        fsr_low = form.getvalue("fsr_low")
        comb_wav = form.getvalue("comb_wav")
        TEC_id = form.getvalue("TEC_id")
        def_temperature = form.getvalue("def_temperature")
        i_drive_id = form.getvalue("i_drive_id")
        set_current = form.getvalue("set_current")
        uuid_cur_set = form.getvalue("uuid_cur_set")

    else:
        demux_id = form_getvalue("demux_id")
        tone = form_getvalue("tone")
        rf_amp_id = form_getvalue("rf_amp_id")
        fsr_high = form_getvalue("fsr_high")
        fsr_low = form_getvalue("fsr_low")
        comb_wav = form_getvalue("comb_wav")
        TEC_id = form_getvalue("TEC_id")
        def_temperature = form_getvalue("def_temperature")
        i_drive_id = form_getvalue("i_drive_id")
        set_current = form_getvalue("set_current")
        uuid_cur_set = form_getvalue("uuid_cur_set")

    #query=c.execute("select count(*) from demux_point_lut where name='"+name+"'")
    # nameCount=c.fetchone()[0]

    if (CCM == true):
        # if nameCount == 0:
        message = "set,element=demux_point_lut,args=13,uuid={0},action={1},demux_id={2},tone={3},rf_amp_id={4},fsr_high={5},fsr_low={6},comb_wav={7},TEC_id={8},def_temperature={9},i_drive_id={10},set_current={11},uuid_cur_set={12},device={13}"\
            .format(cmd_id, cmd, demux_id, tone, rf_amp_id, fsr_high, fsr_low, comb_wav, TEC_id, def_temperature, i_drive_id, set_current, uuid_cur_set, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
        # else:
        #	print(json.JSONEncoder().encode({"status":"fail", "description":"Name Already exists"}))

    else:

        # if (nameCount==0):
        try:
            query = c.execute("insert into demux_point_lut(demux_id,tone,rf_amp_id,fsr_high,fsr_low,comb_wav,TEC_id,def_temperature,i_drive_id,set_current,uuid_cur_set,cr_date) values(?,?,?,?,?,?,datetime())", [
                              cmd_id, cmd, demux_id, tone, rf_amp_id, fsr_high, fsr_low, comb_wav, TEC_id, def_temperature, i_drive_id, set_current, uuid_cur_set])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Created"})))
        except Exception as e:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": str(e)})))

    c.close()
    conn.close()


def update_DemuxPointLut():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        Id = form.getvalue("Id")
        demux_id = form.getvalue("demux_id")
        tone = form.getvalue("tone")
        rf_amp_id = form.getvalue("rf_amp_id")
        fsr_high = form.getvalue("fsr_high")
        fsr_low = form.getvalue("fsr_low")
        comb_wav = form.getvalue("comb_wav")
        TEC_id = form.getvalue("TEC_id")
        def_temperature = form.getvalue("def_temperature")
        i_drive_id = form.getvalue("i_drive_id")
        set_current = form.getvalue("set_current")
        uuid_cur_set = form.getvalue("uuid_cur_set")

    else:
        Id = form_getvalue("id")
        demux_id = form_getvalue("demux_id")
        tone = form_getvalue("tone")
        rf_amp_id = form_getvalue("rf_amp_id")
        fsr_high = form_getvalue("fsr_high")
        fsr_low = form_getvalue("fsr_low")
        comb_wav = form_getvalue("comb_wav")
        TEC_id = form_getvalue("TEC_id")
        def_temperature = form_getvalue("def_temperature")
        i_drive_id = form_getvalue("i_drive_id")
        set_current = form_getvalue("set_current")
        uuid_cur_set = form_getvalue("uuid_cur_set")

    #query=c.execute("select count(*) from demux_point_lut where name=? and id not like ?",[name,id])
    # nameCount=c.fetchone()[0]

    if (CCM == true):
        # if (nameCount==0):
        message = "set,element=demux_point_lut,args=14,uuid={0},action={1},demux_id={2},tone={3},rf_amp_id={4},fsr_high={5},fsr_low={6},comb_wav={7},TEC_id={8},def_temperature={9},i_drive_id={10},set_current={11},uuid_cur_set={12},id={13},device={14}"\
            .format(cmd_id, cmd, demux_id, tone, rf_amp_id, fsr_high, fsr_low, comb_wav, TEC_id, def_temperature, i_drive_id, set_current, uuid_cur_set, Id, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
        # else:
        #	print(json.JSONEncoder().encode({"status":"fail","description":"Name Already exists"}))
    else:
        # if(nameCount==0):
        try:
            query = c.execute("update demux_point_lut set demux_id=?,tone=?,rf_amp_id=?,fsr_high=?,fsr_low=?,comb_wav=?,TEC_id=?,def_temperature=?,i_drive_id=?,set_current=?,uuid_cur_set=?,edit_date=datetime() where id=?",
                              [demux_id, tone, rf_amp_id, fsr_high, fsr_low, comb_wav, TEC_id, def_temperature, i_drive_id, set_current, uuid_cur_set, Id])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated "})))
        except Exception as e:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": str(e)})))

    c.close()
    conn.close()


def delete_DemuxPointLut():

    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        Id = form.getvalue("id")
    else:
        Id = form_getvalue("id")

    if (CCM == true):
        message = "set,element=demux_point_lut,args=3,uuid={0},action={1},id={2},device={3}".format(
            cmd_id, cmd, Id, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        try:
            query = c.execute("delete from demux_point_lut where id="+Id+"")
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Deleted"})))
        except Exception as err:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Failed to Delete "})))
    c.close()
    conn.close()


def read_DemuxPointLut():

    cmd = "read"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        Id = form.getvalue("id")
    else:
        Id = form_getvalue("id")

    query = c.execute(
        "select id,demux_id ,tone ,rf_amp_id ,fsr_high ,fsr_low ,comb_wav ,TEC_id ,def_temperature ,i_drive_id ,set_current ,uuid_cur_set from demux_point_lut where id="+str(Id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "demux_id": col[1], "tone": col[2], "rf_amp_id": col[3], "fsr_high": col[4], "fsr_low": col[5],
                      "comb_wav": col[6], "TEC_id": col[7], "def_temperature": col[7], "i_drive_id": col[8], "set_current": col[9], "uuid_cur_set": col[10]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_DemuxPointLut'):
    create_DemuxPointLut()
elif(request_Type == 'update_DemuxPointLut'):
    update_DemuxPointLut()
elif(request_Type == 'delete_DemuxPointLut'):
    delete_DemuxPointLut()
else:
    read_DemuxPointLut()
