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


def form_getvalue(val):
    if val == "mode_map_id":
        mode_map_id = str(input("Enter mode_map_id of the mode_point_lut: "))
        return mode_map_id
    if val == "wavelength":
        wavelength = str(input("Enter wavelength of the mode_point_lut: "))
        return wavelength
    if val == "smsr":
        smsr = str(input("Enter smsr of the mode_point_lut: "))
        return smsr
    if val == "TEC_id":
        TEC_id = str(input("Enter TEC_id of the mode_point_lut: "))
        return TEC_id
    if val == "def_temperature":
        def_temperature = str(
            input("Enter def_temperature of the mode_point_lut: "))
        return def_temperature
    if val == "i_drive_id":
        i_drive_id = str(input("Enter i_drive_id of the mode_point_lut: "))
        return i_drive_id
    if val == "set_current":
        set_current = str(input("Enter set_current of the mode_point_lut: "))
        return set_current
    if val == "uuid_cur_set":
        uuid_cur_set = str(input("Enter uuid_cur_set of the mode_point_lut: "))
        return uuid_cur_set
    if val == "id":
        id = str(input("Enter id of the mode_point_lut: "))
        return id


def create_mode_point_lut():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        mode_map_id = form.getvalue("mode_map_id")
        wavelength = form.getvalue("wavelength")
        smsr = form.getvalue("smsr")
        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:
        mode_map_id = form_getvalue("mode_map_id")
        wavelength = form_getvalue("wavelength")
        smsr = form_getvalue("smsr")
        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 mode_point_lut where mode_map_id='"+mode_map_id+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=mode_point_lut,args=10,uuid={0},action={1},mode_map_id={2},wavelength={3},smsr={4},TEC_id={5},def_temperature={6},i_drive_id={7},set_current={8},uuid_cur_set={9},device={10}"\
                .format(cmd_id, cmd, mode_map_id, wavelength, smsr, 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):
            query = c.execute("insert into mode_point_lut(mode_map_id,wavelength,smsr,TEC_id,def_temperature,i_drive_id,set_current,uuid_cur_set,cr_date ) values(?,?,?,?,?,?,?,?,datetime())", [
                              mode_map_id, wavelength, smsr, TEC_id, def_temperature, i_drive_id, set_current, uuid_cur_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_mode_point_lut():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        mode_map_id = form.getvalue("mode_map_id")
        wavelength = form.getvalue("wavelength")
        smsr = form.getvalue("smsr")
        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")
        id = form.getvalue("id")
    else:
        mode_map_id = form_getvalue("mode_map_id")
        wavelength = form_getvalue("wavelength")
        smsr = form_getvalue("smsr")
        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")
        id = form_getvalue("id")
    query = c.execute(
        "select count(*) from mode_point_lut where mode_map_id=? and id not like ?", [mode_map_id, id])
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=mode_point_lut,args=11,uuid={0},action={1},mode_map_id={2},wavelength={3},smsr={4},TEC_id={5},def_temperature={6},i_drive_id={7},set_current={8},uuid_cur_set={9},id={10},device={11}"\
                .format(cmd_id, cmd, mode_map_id, wavelength, smsr, 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:
        print("CCM is False")

        if (nameCount == 0):
            query = c.execute("update mode_point_lut set mode_map_id=?,wavelength=?,smsr=?,TEC_id=?,def_temperature=?,i_drive_id=?,set_current=?,uuid_cur_set=?,edit_date=datetime() where id=?", [
                              mode_map_id, wavelength, smsr, TEC_id, def_temperature, i_drive_id, set_current, uuid_cur_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_mode_point_lut():
    cmd = "delete"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        id = form.getvalue("id")
        mode_map_id = form.getvalue("mode_map_id")
    else:
        id = form_getvalue("id")
        mode_map_id = form_getvalue("mode_map_id")
    if (CCM == true):
        message = "set,element=mode_point_lut,args=4,uuid={0},action={1},id={2},mode_map_id={3},device={4}".format(
            cmd_id, cmd, id, mode_map_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 mode_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_mode_point_lut():
    cmd = "read"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = form_getvalue("id")
    query = c.execute(
        "select mode_map_id,wavelength,smsr,TEC_id,def_temperature,i_drive_id,set_current,uuid_cur_set,id from mode_point_lut where id="+str(id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"mode_map_id": col[0], "wavelength": col[1], "smsr": col[2], "TEC_id": col[3],
                      "def_temperature": col[4], "i_drive_id": col[5], "set_current": col[6], "uuid_cur_set": col[7], "id": col[8]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_mode_point_lut'):
    create_mode_point_lut()
elif(request_Type == 'update_mode_point_lut'):
    update_mode_point_lut()
elif(request_Type == 'delete_mode_point_lut'):
    delete_mode_point_lut()
else:
    read_mode_point_lut()
