#!/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 Comb_Point_Lut")
    print("2.Update Comb_Point_Lut")
    print("3.Delete Comb_Point_Lut")
    print("4.Read Comb_Point_Lut")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_comb_point_lut'
    elif choice == 2:
        request_Type = 'update_comb_point_lut'
    elif choice == 3:
        request_Type = 'delete_comb_point_lut'
    elif choice == 4:
        request_Type = 'read_comb_point_lut'
    else:
        print("Enter Valid choice")
    print("Reques_Type="+str(request_Type))


def form_getvalue(val):
    if val == "comb_map_id":
        comb_map_id = str(input("Enter comb_map_id of the comb_point_lut: "))
        return comb_map_id
    if val == "central_wavelength":
        central_wavelength = str(
            input("Enter central_wavelength of the comb_point_lut: "))
        return central_wavelength
    if val == "fsr_high":
        fsr_high = str(input("Enter fsr_high of the comb_point_lut: "))
        return fsr_high
    if val == "fsr_low":
        fsr_low = str(input("Enter fsr_low of the comb_point_lut: "))
        return fsr_low
    if val == "smsr":
        smsr = str(input("Enter smsr of the comb_point_lut: "))
        return smsr
    if val == "rf_amp_id":
        rf_amp_id = str(input("Enter rf_amp_id of the comb_point_lut: "))
        return rf_amp_id
    if val == "def_rf_dB_level":
        def_rf_dB_level = str(
            input("Enter def_rf_dB_level of the comb_point_lut: "))
        return def_rf_dB_level
    if val == "def_fsr_frequency":
        def_fsr_frequency = str(
            input("Enter def_fsr_frequency of the comb_point_lut: "))
        return def_fsr_frequency
    if val == "TEC_id":
        TEC_id = str(input("Enter TEC_id of the comb_point_lut: "))
        return TEC_id
    if val == "def_temperature":
        def_temperature = str(
            input("Enter def_temperature of the comb_point_lut: "))
        return def_temperature
    if val == "i_drive_id":
        i_drive_id = str(input("Enter i_drive_id of the comb_point_lut: "))
        return i_drive_id
    if val == "set_current":
        set_current = str(input("Enter set_current of the comb_point_lut: "))
        return set_current
    if val == "uuid_curr_set":
        uuid_curr_set = str(
            input("Enter uuid_curr_set of the comb_point_lut: "))
        return uuid_curr_set
    if val == "id":
        id = str(input("Enter id of the comb_point_lut: "))
        return id


def create_comb_point_lut():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        comb_map_id = form.getvalue("comb_map_id")
        central_wavelength = form.getvalue("central_wavelength")
        fsr_high = form.getvalue("fsr_high")
        fsr_low = form.getvalue("fsr_low")
        smsr = form.getvalue("smsr")
        rf_amp_id = form.getvalue("rf_amp_id")
        def_rf_dB_level = form.getvalue("def_rf_dB_level")
        def_fsr_frequency = form.getvalue("def_fsr_frequency")
        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_curr_set = form.getvalue("uuid_curr_set")
    else:
        comb_map_id = form_getvalue("comb_map_id")
        central_wavelength = form_getvalue("central_wavelength")
        fsr_high = form_getvalue("fsr_high")
        fsr_low = form_getvalue("fsr_low")
        smsr = form_getvalue("smsr")
        rf_amp_id = form_getvalue("rf_amp_id")
        def_rf_dB_level = form_getvalue("def_rf_dB_level")
        def_fsr_frequency = form_getvalue("def_fsr_frequency")
        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_curr_set = form_getvalue("uuid_curr_set")
    query = c.execute(
        "select count(*) from comb_point_lut where comb_map_id='"+comb_map_id+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=comb_point_lut,args=15,uuid={0},action={1},comb_map_id={2},central_wavelength={3},fsr_high={4},fsr_low={5},smsr={6},rf_amp_id={7},def_rf_dB_level={8},def_fsr_frequency={9},TEC_id={10},def_temperature={11},i_drive_id={12},set_current={13},uuid_curr_set={14}, device={15}"\
                .format(cmd_id, cmd, comb_map_id, central_wavelength, fsr_high, fsr_low, smsr, rf_amp_id, def_rf_dB_level, def_fsr_frequency, TEC_id, def_temperature, i_drive_id, set_current, uuid_curr_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):
            query = c.execute("insert into comb_point_lut(comb_map_id,central_wavelength,fsr_high,fsr_low,smsr,rf_amp_id,def_rf_dB_level,def_fsr_frequency,TEC_id,def_temperature,i_drive_id,set_current,uuid_curr_set,cr_date ) values(?,?,?,?,?,?,?,?,?,?,?,?,?,datetime())", [
                              comb_map_id, central_wavelength, fsr_high, fsr_low, smsr, rf_amp_id, def_rf_dB_level, def_fsr_frequency, TEC_id, def_temperature, i_drive_id, set_current, uuid_curr_set])
            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 update_comb_point_lut():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        comb_map_id = form.getvalue("comb_map_id")
        central_wavelength = form.getvalue("central_wavelength")
        fsr_high = form.getvalue("fsr_high")
        fsr_low = form.getvalue("fsr_low")
        smsr = form.getvalue("smsr")
        rf_amp_id = form.getvalue("rf_amp_id")
        def_rf_dB_level = form.getvalue("def_rf_dB_level")
        def_fsr_frequency = form.getvalue("def_fsr_frequency")
        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_curr_set = form.getvalue("uuid_curr_set")
        id = form.getvalue("id")
    else:
        comb_map_id = form_getvalue("comb_map_id")
        central_wavelength = form_getvalue("central_wavelength")
        fsr_high = form_getvalue("fsr_high")
        fsr_low = form_getvalue("fsr_low")
        smsr = form_getvalue("smsr")
        rf_amp_id = form_getvalue("rf_amp_id")
        def_rf_dB_level = form_getvalue("def_rf_dB_level")
        def_fsr_frequency = form_getvalue("def_fsr_frequency")
        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_curr_set = form_getvalue("uuid_curr_set")
        id = form_getvalue("id")
    query = c.execute(
        "select count(*) from comb_point_lut where comb_map_id=? and id not like ?", [comb_map_id, id])
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=comb_point_lut,args=16,uuid={0},action={1},comb_map_id={2},central_wavelength={3},fsr_high={4},fsr_low={5},smsr={6},rf_amp_id={7},def_rf_dB_level={8},def_fsr_frequency={9},TEC_id={10},def_temperature={11},i_drive_id={12},set_current={13},uuid_curr_set={14},id={15}, device={16}"\
                .format(cmd_id, cmd, comb_map_id, central_wavelength, fsr_high, fsr_low, smsr, rf_amp_id, def_rf_dB_level, def_fsr_frequency, TEC_id, def_temperature, i_drive_id, set_current, uuid_curr_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):
            query = c.execute("update comb_point_lut set comb_map_id=?,central_wavelength=?,fsr_high=?,fsr_low=?,smsr=?,rf_amp_id=?,def_rf_dB_level=?,def_fsr_frequency=?,TEC_id=?,def_temperature=?,i_drive_id=?,set_current=?,uuid_curr_set=?,edit_date=datetime() where id=?", [
                              comb_map_id, central_wavelength, fsr_high, fsr_low, smsr, rf_amp_id, def_rf_dB_level, def_fsr_frequency, TEC_id, def_temperature, i_drive_id, set_current, uuid_curr_set, id])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated"})))
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Name Already exists"})))

    c.close()
    conn.close()


def delete_comb_point_lut():
    cmd = "delete"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        id = form.getvalue("id")
        comb_map_id = form.getvalue("comb_map_id")
    else:
        id = form_getvalue("id")
        comb_map_id = form_getvalue("comb_map_id")
    if (CCM == true):
        message = "set,element=comb_point_lut,args=4,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 comb_point_lut where  id="+str(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_comb_point_lut():
    cmd = "read"
    cmd_id = get_ccm_command_id()
    print("read")
    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = form_getvalue("id")
    query = c.execute("select comb_map_id,central_wavelength,fsr_high,fsr_low,smsr,rf_amp_id,def_rf_dB_level,def_fsr_frequency,TEC_id,def_temperature,i_drive_id,set_current,uuid_curr_set,id from comb_point_lut where id="+str(id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"comb_map_id": col[0], "central_wavelength": col[1], "fsr_high": col[2], "fsr_low": col[3], "smsr": col[4], "rf_amp_id": col[5], "def_rf_dB_level": col[6],
                      "def_fsr_frequency": col[7], "TEC_id": col[8], "def_temperature": col[9], "i_drive_id": col[10], "set_current": col[11], "uuid_curr_set": col[12], "id": col[13]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_comb_point_lut'):
    create_comb_point_lut()
elif(request_Type == 'update_comb_point_lut'):
    update_comb_point_lut()
elif(request_Type == 'delete_comb_point_lut'):
    delete_comb_point_lut()
else:
    read_comb_point_lut()
