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


def form_getvalue(val):
    if val == "state":
        state = str(input("Enter state of the person: "))
        return state
    if val == "userName":
        userName = str(input("Enter userName of the person: "))
        return userName
    if val == "FirstName":
        FirstName = str(input("Enter FirstName of the person: "))
        return FirstName
    if val == "MiddleName":
        MiddleName = str(input("Enter MiddleName of the person: "))
        return MiddleName
    if val == "LastName":
        LastName = str(input("Enter LastName of the person: "))
        return LastName
    if val == "contactEmail":
        contactEmail = str(input("Enter contactEmail of the person: "))
        return contactEmail
    if val == "password":
        password = str(input("Enter password of the person: "))
        return password
    if val == "hyperlink":
        hyperlink = str(input("Enter hyperlink of the person: "))
        return hyperlink
    if val == "contactPhone":
        contactPhone = str(input("Enter contactPhone of the person: "))
        return contactPhone
    if val == "login_time":
        login_time = str(input("Enter login_time of the person: "))
        return login_time
    if val == "num_attempt":
        num_attempt = str(input("Enter num_attempt of the person: "))
        return num_attempt
    if val == "id":
        id = str(input("Enter id of the person: "))
        return id


def create_person():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        state = form.getvalue("state")
        userName = form.getvalue("userName")
        FirstName = form.getvalue("FirstName")
        MiddleName = form.getvalue("MiddleName")
        LastName = form.getvalue("LastName")
        contactEmail = form.getvalue("contactEmail")
        password = form.getvalue("password")
        hyperlink = form.getvalue("hyperlink")
        contactPhone = form.getvalue("contactPhone")
        login_time = form.getvalue("login_time")
        num_attempt = form.getvalue("num_attempt")
    else:
        state = form_getvalue("state")
        userName = form_getvalue("userName")
        FirstName = form_getvalue("FirstName")
        MiddleName = form_getvalue("MiddleName")
        LastName = form_getvalue("LastName")
        contactEmail = form_getvalue("contactEmail")
        password = form_getvalue("password")
        hyperlink = form_getvalue("hyperlink")
        contactPhone = form_getvalue("contactPhone")
        login_time = form_getvalue("login_time")
        num_attempt = form_getvalue("num_attempt")
    query = c.execute(
        "select count(*) from person where userName='"+userName+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=person,args=13,uuid={0},action={1},state={2},userName={3},FirstName={4},MiddleName={5},LastName={6},contactEmail={7},password={8},hyperlink={9},contactPhone={10},login_time={11},num_attempt={12},device={13}"\
                .format(cmd_id, cmd, state, userName, FirstName, MiddleName, LastName, contactEmail, password, hyperlink, contactPhone, login_time, num_attempt, 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 [object Object](state,userName,FirstName,MiddleName,LastName,contactEmail,password,hyperlink,contactPhone,login_time,num_attempt,cr_date ) values(?,?,?,?,?,?,?,?,?,?,?,datetime())", [
                              state, userName, FirstName, MiddleName, LastName, contactEmail, password, hyperlink, contactPhone, login_time, num_attempt])
            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_person():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    print("update")
    if(GUI == true):
        state = form.getvalue("state")
        userName = form.getvalue("userName")
        FirstName = form.getvalue("FirstName")
        MiddleName = form.getvalue("MiddleName")
        LastName = form.getvalue("LastName")
        contactEmail = form.getvalue("contactEmail")
        password = form.getvalue("password")
        hyperlink = form.getvalue("hyperlink")
        contactPhone = form.getvalue("contactPhone")
        login_time = form.getvalue("login_time")
        num_attempt = form.getvalue("num_attempt")
        id = form.getvalue("id")
    else:
        state = form_getvalue("state")
        userName = form_getvalue("userName")
        FirstName = form_getvalue("FirstName")
        MiddleName = form_getvalue("MiddleName")
        LastName = form_getvalue("LastName")
        contactEmail = form_getvalue("contactEmail")
        password = form_getvalue("password")
        hyperlink = form_getvalue("hyperlink")
        contactPhone = form_getvalue("contactPhone")
        login_time = form_getvalue("login_time")
        num_attempt = form_getvalue("num_attempt")
        id = form_getvalue("id")
    query = c.execute(
        "select count(*) from person where userName=? and id not like ?", [userName, id])
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=person,args=14,uuid={0},action={1},state={2},userName={3},FirstName={4},MiddleName={5},LastName={6},contactEmail={7},password={8},hyperlink={9},contactPhone={10},login_time={11},num_attempt={12},id={13},device={14}"\
                .format(cmd_id, cmd, state, userName, FirstName, MiddleName, LastName, contactEmail, password, hyperlink, contactPhone, login_time, num_attempt, 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("update person set state=?,userName=?,FirstName=?,MiddleName=?,LastName=?,contactEmail=?,password=?,hyperlink=?,contactPhone=?,login_time=?,num_attempt=?,id=?,edit_date=datetime() where id=?", [
                              state, userName, FirstName, MiddleName, LastName, contactEmail, password, hyperlink, contactPhone, login_time, num_attempt, 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_person():
    cmd = "delete"
    cmd_id = get_ccm_command_id()
    print("delete")
    if(GUI == true):
        id = form.getvalue("id")
        userName = form.getvalue("userName")
    else:
        id = form_getvalue("id")
        userName = form_getvalue("userName")
    if (CCM == true):
        message = "set,element=person,args=4,uuid={0},action={1},id={2},userName={3},device={4}".format(
            cmd_id, cmd, id, userName, 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 person 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_person():
    cmd = "read"
    cmd_id = get_ccm_command_id()
    print("read")
    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = form_getvalue("id")
    query = c.execute(
        "select state,userName,FirstName,MiddleName,LastName,contactEmail,password,hyperlink,contactPhone,login_time,num_attempt,id from person where id="+str(id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"state": col[0], "userName": col[1], "FirstName": col[2], "MiddleName": col[3], "LastName": col[4], "contactEmail": col[5],
                      "password": col[6], "hyperlink": col[7], "contactPhone": col[8], "login_time": col[9], "num_attempt": col[10], "id": col[11]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_person'):
    create_person()
elif(request_Type == 'update_person'):
    update_person()
elif(request_Type == 'delete_person'):
    delete_person()
else:
    read_person()
