#!/usr/bin/python3

from db import *
from global_func import *
from globalSettings import *
import json
import sqlite3
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 PIC")
    print("2.Read PIC")
    print("3.Update PIC")
    print("4.Delete PIC")

    choice = int(input("Select CGI Function==> "))
    if choice == 1:
        request_Type = "create_PIC"
    elif choice == 2:
        request_Type = "read_PIC"
    elif choice == 3:
        request_Type = "update_PIC"
    elif choice == 4:
        request_Type = "delete_PIC"
    else:
        print("Enter Valid Choice")
    print("Request Type: ", str(request_Type))


def form_getvalue(val):
    if val == "Id":
        picId = str(input("Enter pic ID: "))
        return picId
    elif val == "name":
        picName = str(input("Enter pic Name: "))
        return picName
    elif val == "state":
        picState = int(input("Enter pic State: "))
        return picState
    elif val == "features_id":
        picFeatId = int(input("Enter Features  ID: "))
        return picFeatId
    elif val == "system_id":
        picSystemId = int(input("Enter System Id : "))
        return picSystemId
    else:
        pass


def create_PIC():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    if (GUI == true):
        #picId = form.getvalue("Id")
        picName = form.getvalue("name")
        #picState = form.getvalue("state")
        picFeatId = form.getvalue("features_id")
        picSystemId = form.getvalue("system_id")

    else:
        #picId = form_getvalue("Id")
        picName = form_getvalue("name")
        #picState = form_getvalue("state")
        picFeatId = form_getvalue("features_id")
        picSystemId = form_getvalue("system_id")

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

    if (CCM == true):

        if nameCount == 0:
            message = "set,element=PIC,element_name={0},args=5,action={1},state={2},featuresId={3},systemId={4},uuid={5},device={6}".\
                format(picName, cmd, 0, picFeatId, picSystemId, 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 Exist"})))

    else:
        if nameCount == 0:
            query = c.execute("insert into PIC(name,state,features,system_id,cr_date,edit_date) values(?,0,?,?,datetime(),datetime())",
                              [picName, picFeatId, picSystemId])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "sucess", "description": "Successfully Created"})))
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Name Already Exist"})))
    c.close()
    conn.close()


def update_PIC():

    cmd = "update"
    cmd_id = get_ccm_command_id()
    if (GUI == true):
        picId = form.getvalue("Id")
        picName = form.getvalue("name")
        picState = form.getvalue("state")
        picFeatId = form.getvalue("features_id")
        picSystemId = form.getvalue("system_id")

    else:
        picId = form_getvalue("Id")
        picName = form_getvalue("name")
        picState = form_getvalue("state")
        picFeatId = form_getvalue("features_id")
        picSystemId = form_getvalue("system_id")

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

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=PIC,element_name={0},args=6,action={1},Id={2},state={3},featuresId={4},systemId={5},uuid={6},device={7}".\
                format(picName, cmd, picId, picState,
                       picFeatId, picSystemId, 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 Exist"})))
    else:
        if nameCount == 0:
            query = c.execute("update PIC set name=?,state=?,features=?,system_id=?,edit_date=datetime() where id=?",
                              [picName, picState, picFeatId, picSystemId, picId])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "sucess", "description": "Successfully Updated"})))
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Name Already Exist"})))
    c.close()
    conn.close()


def delete_PIC():
    # print "delete_PIC"
    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if (GUI == true):
        picId = form.getvalue("Id")
        picName = form.getvalue("name")
    else:
        picId = form_getvalue("Id")
        picName = form_getvalue("name")

    if (CCM == true):
        message = "set,element=PIC,element_name={0},args=3,action={1},Id={2},uuid={3},device={4}".format(
            picName, cmd, picId, 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 PIC where id='"+str(picId)+"'")
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Deleted"})))
        except Exception as e:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Failed"})))

    c.close()
    conn.close()


def read_PIC():
    cmd = "read"
    if (GUI == true):
        picId = form.getvalue("Id")
    else:
        picId = form_getvalue("Id")

    query = c.execute(
        "select id,name,state,features,system_id from PIC where id='"+picId+"'")
    dbData = []
    conn.commit()
    for col in c:
        jsonSchema = {"Id": col[0], "Name": col[1],
                      "State": col[2], "features": col[3], "system_id": col[4]}
        dbData.append(jsonSchema)
        print((json.JSONEncoder().encode(jsonSchema)))


print("Content-type:/text/html\r\n\r\n")

if request_Type == "create_PIC":
    create_PIC()
elif request_Type == "update_PIC":
    update_PIC()
elif request_Type == "delete_PIC":
    delete_PIC()
else:
    read_PIC()
