#!/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()

device = DeviceName

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

else:
    print("1.Create remote_control")
    print("2.Update remote_control")
    print("3.Delete remote_control")
    print("4.Read remote_control")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_remote_control'
    elif choice == 2:
        request_Type = 'update_remote_control'
    elif choice == 3:
        request_Type = 'delete_remote_control'
    elif choice == 4:
        request_Type = 'read_remote_control'
    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 remote_control: "))
        return name
    if val == "state":
        state = str(input("Enter state of the remote_control: "))
        return state
    if val == "enabled":
        enabled = str(input("Enter enabled of the remote_control: "))
        return enabled
    if val == "userName":
        userName = str(input("Enter userName of the remote_control: "))
        return userName
    if val == "pwd":
        pwd = str(input("Enter pwd of the remote_control: "))
        return pwd
    if val == "id":
        id = str(input("Enter id of the remote_control: "))
        return id


def create_remote_control():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        enabled = form.getvalue("enabled")
        userName = form.getvalue("userName")
        pwd = form.getvalue("pwd")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        enabled = form_getvalue("enabled")
        userName = form_getvalue("userName")
        pwd = form_getvalue("pwd")

    query = c.execute(
        "select name,state,enabled,userName,pwd from remote_control")
    temp = {}
    for col in c:
        temp["name"] = col[0]
        temp["state"] = col[1]
        temp["enabled"] = col[2]
        temp["userName"] = col[3]
        temp["pwd"] = col[4]

    query = c.execute("select count(*) from remote_control")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            name = temp["name"]
            state = temp["state"]
            enabled = temp["enabled"]
            userName = temp["userName"]
            pwd = temp["pwd"]

            message = "set,element=remote_control,args=7,uuid={0},action={1},element_name={2},state={3},enabled={4},userName={5},pwd={6},device={7}"\
                .format(cmd_id, cmd, name, state, enabled, userName, pwd, 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"}))
            update_remote_control()

    else:
        if (nameCount == 0):
            query = c.execute("insert into remote_control(name,state,enabled,userName,pwd,cr_date ) values(?,?,?,?,?,datetime())", [
                              name, state, enabled, userName, pwd])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Created"})))
        else:
            # print(json.JSONEncoder().encode({"status":"fail", "description":"Name Already exists"}))
            update_remote_control()

    # c.close()
    # conn.close()


def update_remote_control():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        enabled = form.getvalue("enabled")
        userName = form.getvalue("userName")
        pwd = form.getvalue("pwd")
        id = form.getvalue("id")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        enabled = form_getvalue("enabled")
        userName = form_getvalue("userName")
        pwd = form_getvalue("pwd")
        id = form_getvalue("id")

    query = c.execute(
        "select name,state,enabled,userName,pwd from remote_control")
    temp = {}
    for col in c:
        temp["name"] = col[0]
        temp["state"] = col[1]
        temp["enabled"] = col[2]
        temp["userName"] = col[3]
        temp["pwd"] = col[4]
    name = temp["name"]
    state = temp["state"]
    #enabled = temp["enabled"]
    userName = temp["userName"]
    pwd = temp["pwd"]

    query = c.execute("select count(*) from remote_control")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount > 0:
            message = "set,element=remote_control,args=8,uuid={0},action={1},element_name={2},state={3},enabled={4},userName={5},pwd={6},device={7}".format(
                cmd_id, cmd, name, state, enabled, userName, pwd, 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 remote_control set name=?,state=?,enabled=?,userName=?,pwd=?,edit_date=datetime()", [
                              name, state, enabled, userName, pwd])
            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_remote_control():
    cmd = "delete"
    cmd_id = get_ccm_command_id()
    print("delete")
    if(GUI == true):
        id = form.getvalue("id")
        name = form.getvalue("name")
    else:
        id = form_getvalue("id")
        name = form_getvalue("name")

    query = c.execute("select name,id from remote_control")
    temp = {}
    for col in c:
        temp["name"] = col[0]
        temp["id"] = col[1]

    name = temp["name"]
    id = temp["state"]

    if (CCM == true):
        message = "set,element=remote_control,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 remote_control")
            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_remote_control():
    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,enabled,userName,pwd,id from remote_control")
    dbData = []
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "enabled": col[2],
                      "userName": col[3], "pwd": col[4], "id": col[5]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:text/html\r\n\r\n")
if(request_Type == 'create_remote_control'):
    create_remote_control()
elif(request_Type == 'update_remote_control'):
    update_remote_control()
elif(request_Type == 'delete_remote_control'):
    delete_remote_control()
else:
    read_remote_control()
