#!/usr/bin/python3

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

#DBPath = "TeraDB.db"
conn = sqlite3.connect(DBPath)
conn.text_factory = str
c = conn.cursor()

device = DeviceName

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

else:
    print("1.Create Demux Map")
    print("2.Update Demux Map")
    print("3.Delete Demux Map")
    print("4.Read Demux Map")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_DemuxMap'
    elif choice == 2:
        request_Type = 'update_DemuxMap'
    elif choice == 3:
        request_Type = 'delete_DemuxMap'
    elif choice == 4:
        request_Type = 'read_DemuxMap'
    else:
        print("Enter Valid choice")
    print("Reques_Type="+str(request_Type))


def form_getvalue(val):
    if val == "name":
        name = str(input("Enter name of the Demux Map: "))
        return name
    if val == "state":
        state = str(input("Enter state of the Demux Map: "))
        return state
    if val == "set_power":
        set_power = str(input("Enter set_power:"))
        return set_power
    if val == "set_tone":
        set_tone = str(input("Enter set_tone of the Demux Map: "))
        return set_tone
    if val == "set_on_off_state":
        set_on_off_state = str(
            (input("Enter set_on_off_state of the Demux Map: ")))
        return set_on_off_state
    if val == "get_demux_smsr":
        get_demux_smsr = str(input("Enter Demux Map get_demux_smsr NUmber: "))
        return get_demux_smsr
    if val == "id":
        id = int(input("Enter ID: "))
        return id
    if val == "demo_demux_power":
        demo_demux_power = int(input("demo_demux_power"))
        return demo_demux_power
    if val == "demo_tone":
        demo_tone = int(input("demo_tone"))
        return demo_tone
    if val == "demo_state":
        demo_state = int(input("demo_state"))
        return demo_state
    if val == "lut_id":
        demux_lut_id = int(input("lut_id"))
        return demux_lut_id


def create_DemuxMap():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        set_output = form.getvalue("set_output")
        set_tone = form.getvalue("set_tone")
        set_on_off_state = form.getvalue("set_on_off_state")
        id = form.getvalue("id")
        tec_id = form.getvalue("tec_id")
        #get_demux_smsr = form.getvalue("get_demux_smsr")

    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        set_output = form_getvalue("set_output")
        set_tone = form_getvalue("set_tone")
        set_on_off_state = form_getvalue("set_on_off_state")
        get_demux_smsr = form_getvalue("get_demux_smsr")

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

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=demux_map,args=7,uuid={0},action={1},element_name={2},state={3},set_output={4},set_tone={5},set_on_off_state={6},get_demux_smsr={7},device={8}"\
                .format(cmd_id, cmd, name, state, set_output, set_tone, set_on_off_state, get_demux_smsr, 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:
        print("CCM is False")

        if (nameCount == 0):
            query = c.execute("insert into demux_map(name,state,set_output,set_tone,set_on_off_state,get_demux_smsr,cr_date) values(?,?,?,?,?,?,datetime())", [
                              name, state, set_output, set_tone, set_on_off_state, get_demux_smsr])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Created"})))
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Name Already exists"})))

    c.close()
    conn.close()


def read_CombTone():

    #query=c.execute("select id,tone,comb_central_wav from demux_point_lut")
    query = c.execute("select Dl.id,Dl.tone,Dl.comb_central_wav from demux_point_lut Dl INNER JOIN comb_map CM WHERE Dl.comb_central_wav=CM.set_central_wavelength and (CM.set_comb_FSR BETWEEN Dl.fsr_low and Dl.fsr_high)")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "tone": col[1], "comb_central_wav": col[2]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))
    c.close()
    conn.close()


def read_DemoCombTone():
    query = c.execute("select Dl.id,Dl.tone,Dl.comb_central_wav from demux_point_lut Dl INNER JOIN comb_map CM WHERE Dl.comb_central_wav=CM.demo_central_wave and (CM.demo_FSR BETWEEN Dl.fsr_low and Dl.fsr_high)")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "tone": col[1], "comb_central_wav": col[2]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))
    c.close()
    conn.close()


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

    if(GUI == true):
        demuxId = form.getvalue("id")
        set_demux_power = form.getvalue("set_power")
        # This is the integer value ending in 'COMB TONE 1,COMB TONE 2,COMB Tone3.... the value should be saved as 1,2,3...'
        set_tone = form.getvalue("set_tone")
        set_on_off_state = form.getvalue("set_on_off_state")
        # this value should be the id generated when we select the combTONE from the dropdowns
        demux_lut_id = form.getvalue("lut_id")
    else:
        demuxId = form_getvalue("id")
        set_demux_power = form_getvalue("set_power")
        set_tone = form_getvalue("set_tone")
        set_on_off_state = form_getvalue("set_on_off_state")
        demuxId = form_getvalue("id")
        demux_lut_id = form_getvalue("lut_id")

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

    if nameCount != 0:
        query2 = c.execute("update demux_map set set_tone=null where set_tone=? and id not like ?", [
                           set_tone, demuxId])
        conn.commit()
        #nameCount = 0
        query = c.execute(
            "select count(*) from demux_map where set_tone=? and id not like ?", [set_tone, demuxId])
        nameCount = c.fetchone()[0]
    else:
        pass

    if (CCM == true):
        if (nameCount == 0):
            c.execute("select name,state from demux_map where id='"+demuxId+"'")
            for col in c:
                name = col[0]
                state = col[1]

            message = "set,element=demux_map,args=7,uuid={0},action={1},element_name={2},state={3},set_tone={4},set_on_off_state={5},set_demux_power={6},id={7},demux_lut_id={8},device={9}"\
                .format(cmd_id, cmd, name, state, set_tone, set_on_off_state, set_demux_power, demuxId, demux_lut_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):
            query = c.execute("update demux_map set set_demux_power=?,set_tone=?,set_on_off_state=?,edit_date=datetime() where id=?",
                              [set_demux_power, set_tone, set_on_off_state, demuxId])
            conn.commit()
            # Demux_map_lut
            query2 = c.execute(
                "select count(*) from demux_point_lut where demux_id=?", [str(demuxId)])
            idCount = c.fetchone()[0]
            if idCount == 0:
                query = c.execute("update demux_point_lut set demux_id=?,edit_date=datetime() where id=?", [
                                  str(demuxId), str(demux_lut_id)])
                conn.commit()
            else:
                query = c.execute(
                    "update demux_point_lut set demux_id=null where demux_id=?", [str(demuxId)])
                conn.commit()
                query = c.execute("update demux_point_lut set demux_id=?,edit_date=datetime() where id=?", [
                                  str(demuxId), str(demux_lut_id)])
                conn.commit()

            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated "})))
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Comb Tone Used By Other DEMUX"})))

    c.close()
    conn.close()


def update_DemoDemuxMap():
    cmd = "updateDemo"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        demuxMapId = form.getvalue("id")
        demo_demux_power = form.getvalue("set_power")
        demo_tone = form.getvalue("demo_set_tone")
        demo_set_on_off_state = form.getvalue("set_on_off_state")
        demux_lut_id = form.getvalue("demo_demux_lut_id")
    else:
        demuxMapId = form_getvalue("id")
        demo_demux_power = form_getvalue("demo_demux_power")
        demo_tone = form_getvalue("demo_tone")
        demo_state = form_getvalue("demo_state")
        demux_lut_id = form_getvalue("lut_id")

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

    if nameCount != 0:
        query2 = c.execute("update demux_map set demo_tone=null where demo_tone=? and id not like ?", [
                           demo_tone, demuxMapId])
        conn.commit()
        #nameCount = 0
        query = c.execute(
            "select count(*) from demux_map where demo_tone=? and id not like ?", [demo_tone, demuxMapId])
        nameCount = c.fetchone()[0]
    else:
        pass

    if (CCM == true):
        if (nameCount == 0):
            c.execute(
                "select name,state from demux_map where id='"+demuxMapId+"'")
            for col in c:
                name = col[0]
                state = col[1]
            message = "set,element=demux_map,args=7,uuid={0},action={1},element_name={2},state={3},demo_tone={4},demo_set_on_off={5},demo_demux_power={6},id={7},demux_lut_id={8},device={9}"\
                .format(cmd_id, cmd, name, state, demo_tone, demo_set_on_off_state, demo_demux_power, demuxMapId, demux_lut_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):
            query = c.execute("update demux_map set demo_demux_power=?,demo_tone=?,demo_set_on_off=?,edit_date=datetime() where id=?",
                              [demo_demux_power, demo_tone, demo_set_on_off_state, demuxMapId])
            conn.commit()
            # Demux_map_lut
            query2 = c.execute(
                "select count(*) from demux_point_lut where demo_demux_id=?", [str(demuxMapId)])
            idCount = c.fetchone()[0]
            if idCount == 0:
                query = c.execute("update demux_point_lut set demo_demux_id=?,edit_date=datetime() where id=?", [
                                  str(demuxMapId), str(demux_lut_id)])
                conn.commit()
            else:
                query = c.execute(
                    "update demux_point_lut set demo_demux_id=null where demo_demux_id=?", [str(demuxMapId)])
                conn.commit()
                query = c.execute("update demux_point_lut set demo_demux_id=?,edit_date=datetime() where id=?", [
                                  str(demuxMapId), str(demux_lut_id)])
                conn.commit()

            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated "})))
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Comb Tone Used By Other DEMUX"})))
    c.close()
    conn.close()


def delete_DemuxMap():

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

    if (CCM == true):
        message = "set,element=demux_map,args=7,uuid={0},action={1},element_name={2},id={3},device={4}".format(
            cmd_id, cmd, name, 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_map 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_DemuxMap():
    if(GUI == true):
        demuxId = form.getvalue("id")
        name = form.getvalue("name")
    else:
        name = form_getvalue("name")
        demuxId = form_getvalue("id")

    query = c.execute("select d.id,d.name,d.state,d.set_on_off_state,d.get_demux_power,d.get_max_Demux_power,d.set_demux_power,d.set_tone,lut.tone,lut.id from demux_map d inner join demux_point_lut lut where d.id = lut.demux_id order by d.name")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "name": col[1], "state": col[2], "set_on_off_state": col[3], "get_demux_power": col[4],
                      "get_max_Demux_power": col[5], "set_demux_power": col[6], "set_tone": col[7], "tone_name": col[8], "lut_id": col[9]}
        dbData.append(jsonSchema)

    if dbData == []:
        query = c.execute(
            "select id,name,state,set_on_off_state,get_demux_power,get_max_Demux_power,set_demux_power,set_tone,demo_tone,demo_demux_power,demo_set_on_off from demux_map")
        dbData1 = []
        for col in c:
            jsonSchema = {"id": col[0], "name": col[1], "state": col[2], "set_on_off_state": col[3], "get_demux_power": col[4], "get_max_Demux_power": col[5],
                          "set_demux_power": col[6], "set_tone": col[7], "demo_tone": col[8], "demo_demux_power": col[9], "demo_state": col[10]}
            dbData1.append(jsonSchema)
        print((json.JSONEncoder().encode(dbData1)))
    else:
        print((json.JSONEncoder().encode(dbData)))


def read_DemoDemuxMap():

    if(GUI == true):
        demuxId = form.getvalue("id")
        name = form.getvalue("name")
    else:
        name = form_getvalue("name")
        demuxId = form_getvalue("id")

    query = c.execute("select d.id,d.name,d.state,d.get_demux_power,d.get_max_Demux_power,d.demo_tone,d.demo_demux_power,d.demo_set_on_off,lut.tone,lut.id from demux_map d inner join demux_point_lut lut where d.id = lut.demo_demux_id order by d.name")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "name": col[1], "state": col[2], "get_demux_power": col[3], "get_max_Demux_power": col[4],
                      "demo_tone": col[5], "demo_demux_power": col[6], "demo_state": col[7], "tone_name": col[8], "lut_id": col[9]}
        dbData.append(jsonSchema)
    if dbData == []:
        query = c.execute(
            "select id,name,state,set_on_off_state,get_demux_power,get_max_Demux_power,set_demux_power,set_tone,demo_tone,demo_demux_power,demo_set_on_off from demux_map")
        dbData1 = []
        for col in c:
            jsonSchema = {"id": col[0], "name": col[1], "state": col[2], "set_on_off_state": col[3], "get_demux_power": col[4], "get_max_Demux_power": col[5],
                          "set_demux_power": col[6], "set_tone": col[7], "demo_tone": col[8], "demo_demux_power": col[9], "demo_state": col[10]}
            dbData1.append(jsonSchema)
        print((json.JSONEncoder().encode(dbData1)))
    else:
        print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_DemuxMap'):
    create_DemuxMap()
elif(request_Type == 'update_DemuxMap'):
    update_DemuxMap()
elif(request_Type == 'update_DemoDemuxMap'):
    update_DemoDemuxMap()
elif(request_Type == 'delete_DemuxMap'):
    delete_DemuxMap()
elif (request_Type == 'read_CombTone'):
    read_CombTone()
elif (request_Type == 'read_DemoCombTone'):
    read_DemoCombTone()
elif (request_Type == 'read_DemuxMap'):
    read_DemuxMap()
else:
    read_DemoDemuxMap()
