#!/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 Pic_link")
    print("2.Update Pic_link")
    print("3.Delete Pic_link")
    print("4.Read Pic_link")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_pic_link'
    elif choice == 2:
        request_Type = 'update_pic_link'
    elif choice == 3:
        request_Type = 'delete_pic_link'
    elif choice == 4:
        request_Type = 'read_pic_link'
    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 pic_link: "))
        return name
    if val == "state":
        state = str(input("Enter state of the pic_link: "))
        return state
    if val == "pic_id":
        pic_id = str(input("Enter pic_id of the pic_link: "))
        return pic_id
    if val == "function_id":
        function_id = str(input("Enter function_id of the pic_link: "))
        return function_id
    if val == "features_id":
        features_id = str(input("Enter features_id of the pic_link: "))
        return features_id
    if val == "id":
        id = str(input("Enter id of the pic_link: "))
        return id


def create_pic_link():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        pic_id = form.getvalue("pic_id")
        function_id = form.getvalue("function_id")
        features_id = form.getvalue("features_id")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        pic_id = form_getvalue("pic_id")
        function_id = form_getvalue("function_id")
        features_id = form_getvalue("features_id")
    query = c.execute("select count(*) from pic_link where name='"+name+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=pic_link,args=7,uuid={0},action={1},element_name={2},state={3},pic_id={4},function_id={5},features_id={6},device={7}"\
                .format(cmd_id, cmd, name, state, pic_id, function_id, features_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 pic_link(name,state,pic_id,function_id,features_id,cr_date ) values(?,?,?,?,?,datetime())", [
                              name, state, pic_id, function_id, features_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_pic_link():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        pic_id = form.getvalue("pic_id")
        function_id = form.getvalue("function_id")
        features_id = form.getvalue("features_id")
        id = form.getvalue("id")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        pic_id = form_getvalue("pic_id")
        function_id = form_getvalue("function_id")
        features_id = form_getvalue("features_id")
        id = form_getvalue("id")
    query = c.execute(
        "select count(*) from pic_link where name=? and id not like ?", [name, id])
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=pic_link,args=8,uuid={0},action={1},element_name={2},state={3},pic_id={4},function_id={5},features_id={6},id={7},device={8}"\
                .format(cmd_id, cmd, name, state, pic_id, function_id, features_id, 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 pic_link set name=?,state=?,pic_id=?,function_id=?,features_id=?,edit_date=datetime() where id=?", [
                              name, state, pic_id, function_id, features_id, 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_pic_link():
    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=pic_link,args=4,uuid={0},action={1},id={2},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 pic_link 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_pic_link():
    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,pic_id,function_id,features_id,id from pic_link where id="+str(id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "pic_id": col[2],
                      "function_id": col[3], "features_id": 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_pic_link'):
    create_pic_link()
elif(request_Type == 'update_pic_link'):
    update_pic_link()
elif(request_Type == 'delete_pic_link'):
    delete_pic_link()
else:
    read_pic_link()
