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


def form_getvalue(val):
    if val == "name":
        secName = str(input("Enter name of the Section: "))
        return secName
    if val == "state":
        secState = str(input("Enter State of the Section: "))
        return secState
    if val == "Id":
        secId = str((input("Enter Id of the Section: ")))
        return secId
    if val == "i_drive_id":
        iDriveId = str(input("Enter i_DriveId: "))
        return iDriveId


def create_Section():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        #secId = form.getvalue("Id")
        secName = form.getvalue("name")
        secState = form.getvalue("state")
        iDrive = form.getvalue("i_drive_id")

    else:
        secName = form_getvalue("name")
        secState = form_getvalue("state")
        iDrive = form_getvalue("i_drive_id")

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

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=section,args=4,element_name={0},action={1},state={2},i_drive_id={3},uuid={4},device={5}"\
                .format(secName, cmd, secState, iDrive, 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:
        print("CCM is False")

        if (nameCount == 0):
            query = c.execute("insert into section(name,state,i_drive_id,cr_date) values(?,?,?,datetime())", [
                              secName, secState, iDrive])
            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_Section():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        #secId = form.getvalue("Id")
        secName = form.getvalue("name")
        secState = form.getvalue("state")
        iDrive = form.getvalue("i_drive_id")
        secId = form.getvalue("Id")

    else:
        secName = form_getvalue("name")
        secState = form_getvalue("state")
        iDrive = form_getvalue("i_drive_id")
        secId = form_getvalue("Id")

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

    if (CCM == true):
        if (nameCount == 0):
            message = "set,element=section,args=5,element_name={0},action={1},state={2},i_drive_id={3},id={4},uuid={5},device={6}"\
                .format(secName, cmd, secState, iDrive, secId, 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 section set name=?,state=?,i_drive_id=?,edit_date=datetime() where id=?",
                              [secName, secState, iDrive, secId])
            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_Section():

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

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

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


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_Section'):
    create_Section()
elif(request_Type == 'update_Section'):
    update_Section()
elif(request_Type == 'delete_Section'):
    delete_Section()
else:
    read_Section()
