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

dbFileName = DBPath.split("/")[-1]
device = DeviceName

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

else:
    print("1.Create Comb_Map")
    print("2.Update Comb_Map")
    print("3.Delete Comb_Map")
    print("4.Read Comb_Map")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_comb_map'
    elif choice == 2:
        request_Type = 'update_comb_map'
    elif choice == 3:
        request_Type = 'delete_comb_map'
    elif choice == 4:
        request_Type = 'read_comb_map'
    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 comb_map: "))
        return name
    if val == "state":
        state = str(input("Enter state of the comb_map: "))
        return state
    if val == "set_on_off_state":
        set_on_off_state = str(
            input("Enter set_on_off_state of the comb_map: "))
        return set_on_off_state
    if val == "set_central_wavelength":
        set_central_wavelength = str(
            input("Enter set_central_wavelength of the comb_map: "))
        return set_central_wavelength
    if val == "set_FSR":
        set_FSR = str(input("Enter set_FSR of the comb_map: "))
        return set_FSR
    if val == "set_min_smsr":
        set_min_smsr = str(input("Enter set_min_smsr of the comb_map: "))
        return set_min_smsr
    if val == "set_optimisation_mode":
        set_optimisation_mode = str(
            input("Enter set_optimisation_mode of the comb_map: "))
        return set_optimisation_mode
    if val == "get_nb_tones":
        get_nb_tones = str(input("Enter get_nb_tones of the comb_map: "))
        return get_nb_tones
    if val == "get_linewidth":
        get_linewidth = str(input("Enter get_linewidth of the comb_map: "))
        return get_linewidth
    if val == "id":
        id = str(input("Enter id of the comb_map: "))
        return id
    if val == "demo_wavelength":
        demo_wavelength = str(input("demo_wavelength"))
        return demo_wavelength
    if val == "demo_FSR":
        demo_FSR = str(input("demo_FSR"))
        return demo_FSR


def create_comb_map():
    cmd = "create"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        set_on_off_state = form.getvalue("set_on_off_state")
        set_central_wavelength = form.getvalue("set_central_wavelength")
        set_FSR = form.getvalue("set_FSR")
        set_min_smsr = form.getvalue("set_min_smsr")
        set_optimisation_mode = form.getvalue("set_optimisation_mode")
        get_nb_tones = form.getvalue("get_nb_tones")
        get_linewidth = form.getvalue("get_linewidth")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        set_on_off_state = form_getvalue("set_on_off_state")
        set_central_wavelength = form_getvalue("set_central_wavelength")
        set_FSR = form_getvalue("set_FSR")
        set_min_smsr = form_getvalue("set_min_smsr")
        set_optimisation_mode = form_getvalue("set_optimisation_mode")
        get_nb_tones = form_getvalue("get_nb_tones")
        get_linewidth = form_getvalue("get_linewidth")
    query = c.execute("select count(*) from comb_map where name='"+name+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=comb_map,args=11,uuid={0},action={1},element_name={2},state={3},set_on_off_state={4},set_central_wavelength={5},set_FSR={6},set_min_smsr={7},set_optimisation_mode={8},get_nb_tones={9},get_linewidth={10},device={11}"\
                .format(cmd_id, cmd, name, state, set_on_off_state, set_central_wavelength, set_FSR, set_min_smsr, set_optimisation_mode, get_nb_tones, get_linewidth, 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_map(name,state,set_on_off_state,set_central_wavelength,set_FSR,set_min_smsr,set_optimisation_mode,get_nb_tones,get_linewidth,cr_date ) values(?,?,?,?,?,?,?,?,?,datetime())", [
                              name, state, set_on_off_state, set_central_wavelength, set_FSR, set_min_smsr, set_optimisation_mode, get_nb_tones, get_linewidth])
            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_map():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        #set_on_off_state = form.getvalue("set_on_off_state")
        set_central_wavelength = form.getvalue("set_central_wavelength")
        set_comb_FSR = form.getvalue("set_comb_FSR")
        id = form.getvalue("id")

    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        set_on_off_state = form_getvalue("set_on_off_state")
        set_central_wavelength = form_getvalue("set_central_wavelength")
        set_comb_FSR = form_getvalue("set_FSR")
        #sset_min_smsr = form_getvalue("set_min_smsr")
        id = form_getvalue("id")
    query = c.execute(
        "select count(*) from comb_map where name=? and id not like ?", [name, id])
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            c.execute("select name,state from comb_map where id='"+str(id)+"'")
            for col in c:
                name = col[0]
                state = col[1]
            message = "set,element=comb_map,args=9,uuid={0},action={1},element_name={2},state={3},set_central_wavelength={4},set_comb_FSR={5},id={6},device={7}"\
                .format(cmd_id, cmd, name, state, set_central_wavelength, set_comb_FSR, 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_map set set_central_wavelength=?,set_comb_FSR=?,edit_date=datetime() where id=?", [
                              set_central_wavelength, set_comb_FSR, 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 update_state_comb_map():
    cmd = "updateOnOff"
    cmd_id = get_ccm_command_id()
    set_on_off_state = form.getvalue("set_on_off_state")
    id = form.getvalue("id")
    # demo_state = form.getvalue("demo_state")
    set_frequency_state = form.getvalue("set_frequency_state")
    # set_demo_frequency_state = form.getvalue("set_demo_frequency_state")

    if(CCM == true):
        message = "set,element=comb_map,args=5,uuid={0},action={1},set_on_off_state={2},id={3},set_frequency_state={4},device={5}"\
            .format(cmd_id, cmd, set_on_off_state, id, set_frequency_state, device)

        # if dbFileName not in["OCS_1000DB.db","OCS_1100DB.db","PPS_1000DB.db"]:
        #	message = "set,element=comb_map,args=5,uuid={0},action={1},set_on_off_state={2},demo_set_on_off={3},id={4},device={5}"\
        #	.format(cmd_id,cmd,set_on_off_state,demo_state,id,device)
        # else:
        #	message = "set,element=comb_map,args=5,uuid={0},action={1},set_on_off_state={2},demo_set_on_off={3},id={4},set_frequency_state={5},set_demo_frequency_state={6},device={7}"\
        #	.format(cmd_id,cmd,set_on_off_state,demo_state,id,set_frequency_state,set_demo_frequency_state,device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        query = c.execute("update comb_map set set_on_off_state=?,set_frequency_state=?,edit_date=datetime() where id=?", [
                          set_on_off_state, set_frequency_state, id])
        conn.commit()
        print((json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Updated"})))
        c.close()
        conn.close()

def update_demo_state_comb_map():
    cmd = "updateOnOff"
    cmd_id = get_ccm_command_id()
    # set_on_off_state = form.getvalue("set_on_off_state")
    id = form.getvalue("id")
    demo_state = form.getvalue("demo_state")
    # set_frequency_state = form.getvalue("set_frequency_state")
    set_demo_frequency_state = form.getvalue("set_demo_frequency_state")

    if(CCM == true):
        message = "set,element=comb_map,args=5,uuid={0},action={1},demo_set_on_off={2},id={3},set_demo_frequency_state={4},device={5}"\
            .format(cmd_id, cmd, set_on_off_state, demo_state, id, set_demo_frequency_state, device)

        # if dbFileName not in["OCS_1000DB.db","OCS_1100DB.db","PPS_1000DB.db"]:
        #	message = "set,element=comb_map,args=5,uuid={0},action={1},set_on_off_state={2},demo_set_on_off={3},id={4},device={5}"\
        #	.format(cmd_id,cmd,set_on_off_state,demo_state,id,device)
        # else:
        #	message = "set,element=comb_map,args=5,uuid={0},action={1},set_on_off_state={2},demo_set_on_off={3},id={4},set_frequency_state={5},set_demo_frequency_state={6},device={7}"\
        #	.format(cmd_id,cmd,set_on_off_state,demo_state,id,set_frequency_state,set_demo_frequency_state,device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        query = c.execute("update comb_map set demo_set_on_off=?,set_demo_frequency_state=?,edit_date=datetime() where id=?", [
                           demo_state, set_demo_frequency_state, id])
        conn.commit()
        print((json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Updated"})))
        c.close()
        conn.close()


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

    if(GUI == true):
        id = form.getvalue("id")
        name = form.getvalue("name")
    else:
        id = form_getvalue("id")
        name = form_getvalue("name")
    if (CCM == true):
        message = "set,element=comb_map,args=4,uuid={0},action={1},id={2},name={3},device={4}".format(
            cmd_id, cmd, id, name, 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_map 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_map():
    cmd = "read"
    cmd_id = get_ccm_command_id()
    # print "read"
    # if(GUI == true):
    #     id = form.getvalue("id")
    # else:
    if(wavelengthRange == 'Lyra-TL-5'):
        id = 2
    else:
        id = 3
        # id = form_getvalue("id")

    query = c.execute("select name,state,set_on_off_state,get_min_central_wavelength,get_max_central_wavelength,\
		ifnull(set_central_wavelength,get_min_central_wavelength),get_min_FSR,get_max_FSR,ifnull(set_comb_FSR,get_min_FSR),id,demo_central_wave,demo_FSR,demo_set_on_off,set_frequency_state,set_demo_frequency_state from comb_map where id="+str(id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "set_on_off_state": col[2], "get_min_central_wavelength": col[3], "get_max_central_wavelength": col[4], "set_central_wavelength": col[5], "get_min_FSR": col[6],
                      "get_max_FSR": col[7], "set_comb_FSR": col[8], "id": col[9], "demoWavelength": col[10], "demoFSR": col[11], "demoState": col[12], "setFrequencyState": col[13], "setDemoFrequencyState": col[14]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


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

    if(GUI == true):
        id = form.getvalue("id")
        demo_wavelength = form.getvalue("demo_wavelength")
        demo_FSR = form.getvalue("demo_FSR")

    else:
        id = form_getvalue("id")
        demo_wavelength = form_getvalue("demo_wavelength")
        demo_FSR = form_getvalue("demo_FSR")

    if (CCM == true):
        c.execute("select name from comb_map where id='"+str(id)+"'")
        for col in c:
            name = col[0]

        message = "set,element=comb_map,args=9,uuid={0},action={1},element_name={2},demoWave={3},demoFSR={4},id={5},device={6}"\
            .format(cmd_id, cmd, name, demo_wavelength, demo_FSR, id, device)

        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)

    else:
        query = c.execute("update comb_map set demo_central_wave=?,demo_FSR=?,edit_date=datetime() where id=?", [
                          demo_wavelength, demo_FSR, id])
        conn.commit()
        print((json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Updated"})))

    c.close()
    conn.close()


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_comb_map'):
    create_comb_map()
elif(request_Type == 'update_comb_map'):
    update_comb_map()
elif(request_Type == 'update_state_comb_map'):
    update_state_comb_map()
elif(request_Type == 'update_demo_state_comb_map'):
    update_demo_state_comb_map()
elif(request_Type == 'update_demo_comb_map'):
    update_DemoComb()
elif(request_Type == 'delete_comb_map'):
    delete_comb_map()
else:
    read_comb_map()
