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


def form_getvalue(val):
    if val == "name":
        sysName = str(input("Enter name of the System: "))
        return sysName
    if val == "type":
        sysType = str(input("Enter type of the System: "))
        return sysType
    if val == "description":
        sysDesc = str(input("Enter Description:"))
        return sysDesc
    if val == "state":
        sysState = str(input("Enter State of the System: "))
        return sysState
    if val == "Id":
        sysId = str((input("Enter Id of the System: ")))
        return sysId

    if val == "serial":
        sysSerialNum = str(input("Enter System Serial NUmber: "))
        return sysSerialNum
    if val == "manufacturer":
        sysManufacturer = str(input("Enter sysManufacturer: "))
        return sysManufacturer


def create_System():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        #sysId = form.getvalue("Id")
        sysName = form.getvalue("name")
        sysType = form.getvalue("type")
        sysDesc = form.getvalue("description")
        sysState = form.getvalue("state")
        sysSerialNum = form.getvalue("serial")
        sysManufacturer = form.getvalue("manufacturer")

    else:
        sysName = form_getvalue("name")
        sysType = form_getvalue("type")
        sysDesc = form_getvalue("description")
        sysState = 0  # form_getvalue("state")
        sysSerialNum = form_getvalue("serial")
        sysManufacturer = form_getvalue("manufacturer")

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

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=system,element_name={0},args=7,action={1},sysType={2},sysDesc={3},sysState={4},sysSerialNum={5},sysManufacturer={6},uuid={7},device={8}"\
                .format(sysName, cmd, sysType, sysDesc, sysState, sysSerialNum, sysManufacturer, 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 system(name,type,description,state,serial_number,manufacturer,cr_date) values(?,?,?,?,?,?,datetime())", [
                              sysName, sysType, sysDesc, sysState, sysSerialNum, sysManufacturer])
            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_System():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        sysId = form.getvalue("Id")
        sysName = form.getvalue("name")
        sysType = form.getvalue("type")
        sysDesc = form.getvalue("description")
        sysState = form.getvalue("state")
        sysSerialNum = form.getvalue("serial")
        sysManufacturer = form.getvalue("manufacturer")

    else:
        sysName = form_getvalue("name")
        sysType = form_getvalue("type")
        sysDesc = form_getvalue("description")
        sysState = form_getvalue("state")
        sysId = form_getvalue("Id")
        sysSerialNum = form_getvalue("serial")
        sysManufacturer = form_getvalue("manufacturer")

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

    if (CCM == true):
        if (nameCount == 0):
            message = "set,element=system,element_name={0},args=6,action={1},sysType={2},sysDesc={3},sysState={4},sysId={5},uuid={6},device={7}"\
                .format(sysName, cmd, sysType, sysDesc, sysState, sysId, 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 system set name=?,type=?,description=?,state=?,serial_number=?,manufacturer=?,edit_date=datetime() where id=?",
                              [sysName, sysType, sysDesc, sysState, sysSerialNum, sysManufacturer, sysId])
            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_System():

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

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

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


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_System'):
    create_System()
elif(request_Type == 'update_System'):
    update_System()
elif(request_Type == 'delete_System'):
    delete_System()
else:
    read_System()
