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

device = DeviceName

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

else:
    print("1.Create Section")
    print("2.Update Section")
    print("3.Delete Section")
    print("4.Read Section")
    choice = int(input("select cgi Function===>"))

    if choice == 4:
        request_Type = 'read_Section'
    else:
        print("Enter Valid choice")
    print("Reques_Type="+str(request_Type))


def form_getvalue(val):
    if val == "picId":
        picId = str(input("Enter picId of the Device: "))
        return picId


def read_Section():
    if(GUI == true):
        picId = form.getvalue("picId")
    else:
        picId = form_getvalue("picId")

    queryStr = ''' SELECT PIC.id as PICId, PIC.name as PICName, Features.id as FeatureId, Features.name as FeatureName, function.id as FuctionId, function.name as FuctionName, section.id as SectionId, section.name as SectionName, i_drive.id as IDriveId, i_drive.name as IDriveName,
                   i_drive.set_on_off_state as OnOffState,i_drive.set_min_current as MinValue,i_drive.set_current as SetValue,i_drive.set_current_limit as MaxValue,i_drive.state as State,i_drive.get_current as GetCurrent
                   FROM PIC 
                   INNER JOIN Features ON PIC.id = Features.pic_id
                   INNER JOIN function ON function.feature_id = Features.id
                   INNER JOIN section ON section.function_id = function.id
                   INNER JOIN i_drive ON i_drive.id = section.i_drive_id
                   WHERE PIC.id = 1
                   ORDER BY PIC.id,Features.id,function.id,section.id,i_drive.id
    
                    '''
    query = c.execute(queryStr)
    dbData = []
    for col in c:
        jsonSchema = {"PICId": col[0], "PICName": col[1], "FeatureId": col[2], "FeatureName": col[3], "FuctionId": col[4], "FuctionName": col[5], "SectionId": col[6], "SectionName": col[7],
                      "IDriveId": col[8], "IDriveName": col[9], "OnOffState": col[10] == 1, "MinValue": col[11], "SetValue": col[12], "MaxValue": col[13], "State": col[14], "GetCurrent": col[15]}
        dbData.append(jsonSchema)
        # print json.JSONEncoder().encode(col)
    print(json.JSONEncoder().encode(dbData))


def update_Section():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
        minValue = form.getvalue("minValue")
        maxValue = form.getvalue("maxValue")
        setValue = form.getvalue("setValue")
        onOffState = form.getvalue("onOffState")
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        set_wavelength = form_getvalue("set_wavelength")
        set_min_smsr = form_getvalue("set_min_smsr")
        id = form_getvalue("id")
    query = c.execute("select count(*) from i_drive where id="+str(id))
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=mode_map,args=7,uuid={0},action={1},element_name={2},state={3},set_wavelength={4},set_min_smsr={5},id={6},device={7}"\
                .format(cmd_id, cmd, name, state, set_wavelength, set_min_smsr, 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_current=?,set_on_off_state=?,edit_date=datetime() where id=?", [
                              setValue, onOffState, 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()


print("Content-type:text/html\r\n\r\n")

if(request_Type == 'create_Section'):
    create_Section()
elif(request_Type == 'update_Section'):
    update_Section()
elif(request_Type == 'delete_Section'):
    delete_Section()
else:
    read_Section()
