#!/usr/bin/python3

import time
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')

else:
    print("1.Create Mode_map")
    print("2.Update Mode_map")
    print("3.Delete Mode_map")
    print("4.Read Mode_map")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_mode_map'
    elif choice == 2:
        request_Type = 'update_mode_map'
    elif choice == 3:
        request_Type = 'delete_mode_map'
    elif choice == 4:
        request_Type = 'read_mode_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 mode_map: "))
        return name
    if val == "state":
        state = str(input("Enter state of the mode_map: "))
        return state
    if val == "set_wavelength":
        set_wavelength = str(input("Enter set_wavelength of the mode_map: "))
        return set_wavelength
    if val == "set_min_smsr":
        set_min_smsr = str(input("Enter set_min_smsr of the mode_map: "))
        return set_min_smsr
    if val == "id":
        id = str(input("Enter id of the mode_map: "))
        return id
    if val == "demo_wavelength":
        demo_wavelength = str(input("demo_wavelength"))
        return demo_wavelength
    if val == "demo_smsr":
        demo_smsr = str(input("demo_smsr"))
        return demo_smsr


def create_mode_map():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        set_wavelength = form.getvalue("set_wavelength")
        set_min_smsr = form.getvalue("set_min_smsr")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        set_wavelength = form_getvalue("set_wavelength")
        set_min_smsr = form_getvalue("set_min_smsr")
    query = c.execute("select count(*) from mode_map where name='"+name+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=mode_map,args=6,uuid={0},action={1},element_name={2},state={3},set_wavelength={4},set_min_smsr={5},device={6}"\
                .format(cmd_id, cmd, name, state, set_wavelength, set_min_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:

        if (nameCount == 0):
            query = c.execute("insert into mode_map(name,state,set_wavelength,set_min_smsr,cr_date ) values(?,?,?,?,datetime())", [
                              name, state, set_wavelength, set_min_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 update_mode_map():
    cmd = "update_tl"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        set_wavelength = form.getvalue("set_wavelength")
        set_smsr = form.getvalue("set_min_smsr")
        id = form.getvalue("id")

    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        set_wavelength = form_getvalue("set_wavelength")
        set_min_smsr = form_getvalue("set_min_smsr")
        id = form_getvalue("id")
    query = c.execute("select count(*) from mode_map")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if (nameCount > 0):
            c.execute(
                "select name,get_min_wavelength,get_max_wavelength,get_power,get_max_power,id from mode_map where id ='"+str(id)+"'")
            for col in c:
                name = col[0]
                getMinWave = col[1]
                getMaxWave = col[2]
                getMinSmsr = col[3]
                getMaxSmsr = col[4]
                Id = col[5]

            message = "set,element=mode_map,args=10,uuid={0},action={1},element_name={2},set_wavelength={3},set_power={4},id={5},get_min_wavelength={6},get_max_wavelength={7},get_power={8},get_max_power={9},device={10}"\
                .format(cmd_id, cmd, name, set_wavelength, set_smsr, Id, getMinWave, getMaxWave, getMinSmsr, getMaxSmsr, 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 mode_map set set_wavelength=?,set_power=?,edit_date=datetime() where id = ?", [
                              set_wavelength, set_smsr,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_sml_mode_map():
    cmd = "update_SML"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        set_wavelength = form.getvalue("set_wavelength")
        set_smsr = form.getvalue("get_smsr")
        set_power = form.getvalue("set_power")
        id = form.getvalue("id")

    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        set_wavelength = form_getvalue("set_wavelength")
        set_min_smsr = form_getvalue("set_min_smsr")
        id = form_getvalue("id")
    query = c.execute("select count(*) from mode_map")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if (nameCount > 0):
            c.execute(
                "select name,get_min_wavelength,get_max_wavelength,get_smsr,get_max_smsr,get_power,get_max_power,id from mode_map ")
            for col in c:
                name = col[0]
                getMinWave = col[1]
                getMaxWave = col[2]
                getMinSmsr = col[3]
                getMaxSmsr = col[4]
                getMinPwr = col[5]
                getMaxPwr = col[6]
                Id = col[7]

            message = "set,element=mode_map,args=13,uuid={0},action={1},element_name={2},set_wavelength={3},set_min_smsr={4},id={5},get_min_wavelength={6},get_max_wavelength={7},get_min_smsr={8},get_max_smsr={9},get_power={10},get_max_power={11},set_power={12},device={13}"\
                .format(cmd_id, cmd, name, set_wavelength, set_smsr, Id, getMinWave, getMaxWave, getMinSmsr, getMaxSmsr, getMinPwr, getMaxPwr, set_power, 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 mode_map set set_wavelength=?,set_min_smsr=?,set_power=?,edit_date=datetime()", [
                              set_wavelength, set_smsr, set_power])
            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_mode_map():
    cmd = "updateOnOff"
    cmd_id = get_ccm_command_id()
    id = form.getvalue("id")
    demo_state = form.getvalue("demo_state")
    set_on_off_state = form.getvalue("set_on_off_state")
    set_power_state = form.getvalue("set_power_state")
    set_demo_power_state = form.getvalue("set_demo_power_state")

    if(CCM == true):
        message = "set,element=mode_map,args=5,uuid={0},action={1},state={2},demo_state={3},id={4},set_pwr_state={5},set_demo_pwrState={6},device={7}"\
            .format(cmd_id, cmd, set_on_off_state, demo_state, id, set_power_state, set_demo_power_state, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        query = c.execute("update mode_map set state=?,demo_state=?,set_power_state=?,set_demo_power_state=?,edit_date=datetime() where id=?", [
                          set_on_off_state, demo_state, set_power_state, set_demo_power_state, id])
        conn.commit()
        print((json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Updated"})))
    c.close()
    conn.close()



def delete_mode_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=mode_map,args=4,uuid={0},action={1},id={2},element_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 mode_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_mode_map():
    cmd = "read"
    cmd_id = get_ccm_command_id()

    if(wavelengthRange == 'Lyra-TL-5'):
        id = "(3,4)"
    else:
        id = "(1,2)"
    query = c.execute("select name,get_min_wavelength,get_max_wavelength,set_wavelength,get_smsr,get_max_smsr,set_min_smsr,state,wavelength_interval,id,demo_wavelength,demo_smsr,demo_state,get_power,get_max_power,set_power,demo_set_power,set_power_state,set_demo_power_state,id from mode_map where id in "+id+"")
    dbData = []
    for col in c:
        jsonSchema = {"name": col[0], "minWavelength": col[1], "maxWaveLength": col[2], "setWaveLength": col[3], "minSMSR": col[4], "maxSMSR": col[5], "setSMSR": col[6], "state": col[7] == 1, "wavelengthInterval": col[8], "setMinDR": 0, "setMaxDR": 10,
                      "setDR": 1, "demoWavelength": col[10], "demoSMSR": col[11], "demoState": col[12], "minPower": col[13], "maxPower": col[14], "setPower": col[15], "demoSetPower": col[16], "setPowerState": col[17], "setDemoPowerState": col[18], "id": col[19]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


def update_demoModeMap():

    cmd = "updateDemo"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
        demo_wavelength = form.getvalue("demo_wavelength")
        demo_smsr = form.getvalue("demo_smsr")
        demo_power = form.getvalue("demo_power")
    else:
        id = form_getvalue("id")
        demo_wavelength = form_getvalue("demo_wavelength")
        demo_smsr = form_getvalue("demo_smsr")

    if (CCM == true):
        c.execute("select name from mode_map ")
        for col in c:
            name = col[0]

        message = "set,element=mode_map,args=6,uuid={0},action={1},element_name={2},demo_wavelength={3},demo_smsr={4},id={5},demo_set_power={6},device={7}"\
            .format(cmd_id, cmd, name, demo_wavelength, demo_smsr, id, demo_power, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)

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

    c.close()
    conn.close()


def update_sml_demo_mode_map():

    cmd = "update_SML_Demo"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
        demo_wavelength = form.getvalue("demo_wavelength")
        demo_smsr = form.getvalue("demo_smsr")
        demo_power = form.getvalue("demo_power")
    else:
        id = form_getvalue("id")
        demo_wavelength = form_getvalue("demo_wavelength")
        demo_smsr = form_getvalue("demo_smsr")

    if (CCM == true):
        c.execute("select name from mode_map ")
        for col in c:
            name = col[0]

        message = "set,element=mode_map,args=7,uuid={0},action={1},element_name={2},demo_wavelength={3},demo_smsr={4},demo_set_power={5},id={6},device={7}"\
            .format(cmd_id, cmd, name, demo_wavelength, demo_smsr, demo_power, id, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)

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

    c.close()
    conn.close()


def get_path():
    path1 = r'/var/www/pilot/demographs/ngp/NGP2graph_Single_Mode_Values_.csv'
    path2 = r'/var/www/pilot/demographs/ngp/NGP2graph_Single_Mode_Heatmap_.csv'
    modification_time1 = os.path.getmtime(path1)
    modification_time2 = os.path.getmtime(path2)

    if(modification_time1 > modification_time2):
        print((json.JSONEncoder().encode(
            {"filename": 'NGP2graph_Single_Mode_Values_.csv'})))
    else:
        print((json.JSONEncoder().encode(
            {"filename": 'NGP2graph_Single_Mode_Heatmap_.csv'})))


print("Content-type:text/html\r\n\r\n")
if(request_Type == 'create_mode_map'):
    create_mode_map()
elif(request_Type == 'update_mode_map'):
    update_mode_map()
elif(request_Type == 'update_state_mode_map'):
    update_state_mode_map()
elif(request_Type == 'delete_mode_map'):
    delete_mode_map()
elif(request_Type == 'update_demo_mode_map'):
    update_demoModeMap()
elif(request_Type == 'update_sml_mode_map'):
    update_sml_mode_map()
elif(request_Type == 'update_sml_demo_mode_map'):
    update_sml_demo_mode_map()
elif(request_Type == 'get_path'):
    get_path()
else:
    read_mode_map()
