#!/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 Function")
    print("2.Update Function")
    print("3.Delete Function")
    print("4.Read Function")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_Function'
    elif choice == 2:
        request_Type = 'update_Function'
    elif choice == 3:
        request_Type = 'delete_Function'
    elif choice == 4:
        request_Type = 'read_Function'
    else:
        print("Enter Valid choice")
    print("Request_Type="+str(request_Type))


def form_getvalue(val):
    if val == "name":
        funcName = str(input("Enter name of the Function: "))
        return funcName
    if val == "state":
        funcState = str(input("Enter State of the Function: "))
        return funcState
    if val == "Id":
        funcId = str((input("Enter Id of the Function: ")))
        return funcId
    if val == "type":
        funcType = str(input("Enter Function Type: "))
        return funcType
    if val == "section_id":
        secId = str(input("Enter SectionId: "))
        return secId


def create_Function():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    if(GUI == true):

        funcName = form.getvalue("name")
        funcState = form.getvalue("state")
        funcType = form.getvalue("type")
        secId = form.getvalue("section_id")

    else:
        funcName = form_getvalue("name")
        funcState = form_getvalue("state")
        funcType = form_getvalue("type")
        secId = form_getvalue("section_id")

    query = c.execute(
        "select count(*) from function where name='"+funcName+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=function,args=6,element_name={0},action={1},state={2},section_id={3},type={4},uuid={5},device={6}"\
                .format(funcName, cmd, funcState, secId, funcType, cmd_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("insert into function(name,state,section_id,type,cr_date) values(?,?,?,?,datetime())", [
                              funcName, funcState, secId, funcType])
            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_Function():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):

        funcName = form.getvalue("name")
        funcState = form.getvalue("state")
        funcType = form.getvalue("type")
        secId = form.getvalue("section_id")
        Id = form.getvalue("Id")

    else:
        Id = form_getvalue("Id")
        funcName = form_getvalue("name")
        funcState = form_getvalue("state")
        funcType = form_getvalue("type")
        secId = form_getvalue("section_id")

    query = c.execute(
        "select count(*) from function where name=? and id not like ?", [funcName, Id])
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if (nameCount == 0):
            message = "set,element=function,args=7,element_name={0},action={1},state={2},section_id={3},type={4},id={5},uuid={6},device={7}"\
                .format(funcName, cmd, funcState, secId, funcType, Id, cmd_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 function set name=?,state=?,section_id=?,type=?,edit_date=datetime() where id=?",
                              [funcName, funcState, secId, funcType, 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_Function():

    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if (GUI == true):
        Id = form.getvalue("Id")
        funcName = form.getvalue("name")
    else:
        Id = form_getvalue("Id")
        funcName = form_getvalue("name")

    if (CCM == true):
        message = "set,element=function,args=4,element_name={0},action={1},id={2},uuid={3},device={4}"\
            .format(funcName, 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 function where id="+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_Function():
    if(GUI == true):
        Id = form.getvalue("Id")
        funcName = form.getvalue("name")
    else:
        funcName = form_getvalue("name")
        Id = form_getvalue("Id")

    #query = c.execute("select * from Function where name='"+sysName+"'")
    query = c.execute(
        "select id,name,section_id,state,type from function where id="+str(Id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "name": col[1],
                      "section_id": col[2], "state": col[3], "type": col[4]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_Function'):
    create_Function()
elif(request_Type == 'update_Function'):
    update_Function()
elif(request_Type == 'delete_Function'):
    delete_Function()
else:
    read_Function()
