#!/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=1
# false=0

# GUI=true
# CCM=true

device = DeviceName

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

else:
    print("1.Create I_drive")
    print("2.Update I_drive")
    print("3.Delete I_drive")
    print("4.Read I_drive")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_i_drive'
    elif choice == 2:
        request_Type = 'update_i_drive'
    elif choice == 3:
        request_Type = 'delete_i_drive'
    elif choice == 4:
        request_Type = 'read_i_drive'
    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 i_drive: "))
        return name
    if val == "state":
        state = str(input("Enter state of the i_drive: "))
        return state
    if val == "section_id":
        section_id = str(input("Enter section_id of the i_drive: "))
        return section_id
    if val == "set_on_off_state":
        set_on_off_state = str(
            input("Enter set_on_off_state of the i_drive: "))
        return set_on_off_state
    if val == "set_current_limit":
        set_current_limit = str(
            input("Enter set_current_limit of the i_drive: "))
        return set_current_limit
    if val == "set_min_current":
        set_min_current = str(input("Enter set_min_current of the i_drive: "))
        return set_min_current
    if val == "set_current":
        set_current = str(input("Enter set_current of the i_drive: "))
        return set_current
    if val == "get_current":
        get_current = str(input("Enter get_current of the i_drive: "))
        return get_current
    if val == "get_hardware_id":
        get_hardware_id = str(input("Enter get_hardware_id of the i_drive: "))
        return get_hardware_id
    if val == "id":
        id = str(input("Enter id of the i_drive: "))
        return id


def create_i_drive():
    cmd = "create"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        section_id = form.getvalue("section_id")
        set_on_off_state = form.getvalue("set_on_off_state")
        set_max_current = form.getvalue("set_current_limit")
        set_min_current = form.getvalue("set_min_current")
        set_current = form.getvalue("set_current")
        get_current = form.getvalue("get_current")
        get_hardware_id = form.getvalue("get_hardware_id")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        section_id = form_getvalue("section_id")
        set_on_off_state = form_getvalue("set_on_off_state")
        set_max_current = form_getvalue("set_current_limit")
        set_min_current = form_getvalue("set_min_current")
        set_current = form_getvalue("set_current")
        get_current = form_getvalue("get_current")
        get_hardware_id = form_getvalue("get_hardware_id")
    query = c.execute("select count(*) from i_drive where name='"+name+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=i_drive,args=11,uuid={0},action={1},element_name={2},state={3},section_id={4},set_on_off_state={5},set_max_current={6},set_min_current={7},set_current={8},get_current={9},get_hardware_id={10},device={11}"\
                .format(cmd_id, cmd, name, state, section_id, set_on_off_state, set_max_current, set_min_current, set_current, get_current, get_hardware_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 i_drive(name,state,section_id,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,cr_date ) values(?,?,?,?,?,?,?,?,?,datetime())", [
                              name, state, section_id, set_on_off_state, set_current_limit, set_min_current, set_current, get_current, get_hardware_id])
            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_i_drive():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        set_on_off_state = form.getvalue("set_on_off_state")
        set_current = form.getvalue("set_current")
        id = form.getvalue("id")

        # DEFAULT FACTORY SETTING VALUES

        name = form.getvalue("name")
        #state = form.getvalue("state")
        #set_current_limit = form.getvalue("set_current_limit")
        #set_min_current = form.getvalue("set_min_current")

        #get_current = form.getvalue("get_current")
        #get_hardware_id = form.getvalue("get_hardware_id")

    else:
        set_on_off_state = form_getvalue("set_on_off_state")
        set_current = form_getvalue("set_current")
        id = form_getvalue("id")

        # DEFAULT FACTORY SETTING VALUES
        name = form_getvalue("name")
        #state = form_getvalue("state")
        #section_id = form_getvalue("section_id")
        #set_current_limit = form_getvalue("set_current_limit")
        #set_min_current = form_getvalue("set_min_current")
        #get_current = form_getvalue("get_current")
        #get_hardware_id = form_getvalue("get_hardware_id")

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

    if (CCM == true):
        if nameCount == 0:
            c.execute(
                "select name,state,set_max_current,set_min_current,get_current from i_drive where id="+str(id)+"")
            for col in c:
                name = col[0]
                state = col[1]
                set_max_current = col[2]
                set_min_current = col[3]
                get_current = col[4]

            message = "set,element=i_drive,args=10,uuid={0},action={1},element_name={2},state={3},set_on_off_state={4},set_max_current={5},set_min_current={6},set_current={7},get_current={8},id={9},device={10}"\
                .format(cmd_id, cmd, name, state, set_on_off_state, set_max_current, set_min_current, set_current, get_current, 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 i_drive set set_on_off_state=?,set_current=?,edit_date=datetime() where id=?", [
                              set_on_off_state, set_current, 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_i_drive():
    cmd = "delete"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        id = form.getvalue("id")
        name = form.getvalue("name")
    else:
        id = form_getvalue("id")
        name = form_getvalue("name")
    if (CCM == true):
        message = "set,element=i_drive,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 i_drive 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_i_drive():
    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,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from i_drive")
    dbData = []
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "set_on_off_state": col[2], "set_current_limit": col[3],
                      "set_min_current": col[4], "set_current": col[5], "get_current": col[6], "get_hardware_id": col[7], "id": col[8]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_i_drive'):
    create_i_drive()
elif(request_Type == 'update_i_drive'):
    update_i_drive()
elif(request_Type == 'delete_i_drive'):
    delete_i_drive()
else:
    read_i_drive()
