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

device = DeviceName

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

else:
    print("1.Create Serial")
    print("2.Update Serial")
    print("3.Delete Serial")
    print("4.Read Serial")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_serial'
    elif choice == 2:
        request_Type = 'update_serial'
    elif choice == 3:
        request_Type = 'delete_serial'
    elif choice == 4:
        request_Type = 'read_serial'
    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 serial: "))
        return name
    if val == "state":
        state = str(input("Enter state of the serial: "))
        return state
    if val == "baud_rate":
        baud_rate = str(input("Enter baud_rate of the serial: "))
        return baud_rate
    if val == "id":
        id = str(input("Enter id of the serial: "))
        return id
    if val == "parity":
        serialParity = str(input("Enter Parity: "))
        return serialParity
    if val == "dataBits":
        serialDataBits = str(input("Enter Data Bits: "))
        return serialDataBits
    if val == "flow_control":
        serialFlow = str(input("Enter flow_control: "))
        return serialFlow
    if val == "enabled":
        serialEnabled = str(input("Enter serial enabled: "))
        return serialEnabled


def create_serial():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        baud_rate = form.getvalue("baud_rate")
        parity = form.getvalue("parity")
        data_bits = form.getvalue("data_bits")
        flow_control = form.getvalue("flow_control")
        enabled = form.getvalue("enabled")
        name = "Serial"
        state = "1"
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        baud_rate = form_getvalue("baud_rate")
        flow_control = form_getvalue("flow_control")
        enabled = form_getvalue("enabled")
        parity = form_getvalue("parity")
        data_bits = form_getvalue("data_bits")
        flow_control = form_getvalue("flow_control")
        enabled = form_getvalue("enabled")

    query = c.execute("select count(*) from serial")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=serial,args=9,uuid={0},action={1},element_name={2},state={3},baud_rate={4},parity={5},data_bits={6},flow_control={7},enabled={8},device={9}"\
                .format(cmd_id, cmd, name, state, baud_rate, parity, data_bits, flow_control, enabled, device)
            send_ccm_msg(message)
            response = get_ccm_response(cmd_id)
            print(response)
            delete_ccm_response(cmd_id)
        else:
            update_serial()

    else:

        if (nameCount == 0):
            query = c.execute("insert into serial(baud_rate,parity,data_bits,flow_control,enabled,cr_date ) values(?,?,?,?,?,datetime())", [
                              baud_rate, parity, data_bits, flow_control, enabled])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Created"})))
        else:
            update_serial()

    # c.close()
    # conn.close()


def update_serial():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        baud_rate = form.getvalue("baud_rate")
        parity = form.getvalue("parity")
        data_bits = form.getvalue("data_bits")
        flow_control = form.getvalue("flow_control")
        enabled = form.getvalue("enabled")
        name = "Serial"
        state = "1"
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        baud_rate = form_getvalue("baud_rate")
        id = form_getvalue("id")
        parity = form_getvalue("parity")
        data_bits = form_getvalue("data_bits")
        flow_control = form_getvalue("flow_control")
        enabled = form_getvalue("enabled")

    query = c.execute("select count(*) from serial")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount > 0:
            message = "set,element=serial,args=9,uuid={0},action={1},element_name={2},state={3},baud_rate={4},parity={5},data_bits={6},flow_control={7},enabled={8},device={9}"\
                .format(cmd_id, cmd, name, state, baud_rate, parity, data_bits, flow_control, enabled, 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 serial set baud_rate=?,parity=?,data_bits=?,flow_control=?,enabled=?,edit_date=datetime()", [
                              baud_rate, parity, data_bits, flow_control, enabled])
            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_serial():
    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
        name = form.getvalue("name")
        name = "Serial"
    else:
        id = form_getvalue("id")
        name = form_getvalue("name")

    if (CCM == true):
        message = "set,element=serial,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 serial 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_serial():
    cmd = "read"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = form_getvalue("id")
    query = c.execute(
        "select name,state,baud_rate,parity,data_bits,flow_control,id,enabled from serial")
    dbData = []
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "baud_rate": col[2], "parity": col[3],
                      "data_bits": col[4], "flow_control": col[5], "id": col[6], "enabled": col[7]}
        dbData.append(jsonSchema)
    print(json.JSONEncoder().encode(dbData))


print("Content-type:text/html\r\n\r\n")
if(request_Type == 'create_serial'):
    create_serial()
elif(request_Type == 'update_serial'):
    update_serial()
elif(request_Type == 'delete_serial'):
    delete_serial()
else:
    read_serial()
