#!/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 RF Amp")
    print("2.Update RF Amp")
    print("3.Delete RF Amp")
    print("4.Read RF Amp")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_RFAmp'
    elif choice == 2:
        request_Type = 'update_RFAmp'
    elif choice == 3:
        request_Type = 'delete_RFAmp'
    elif choice == 4:
        request_Type = 'read_RFAmp'
    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 RF Amp: "))
        return name
    if val == "state":
        state = str(input("Enter state of the RF Amp: "))
        return state
    if val == "section_id":
        section_id = str(input("Enter section_id:"))
        return section_id
    if val == "set_Frequency":
        set_fsr_frequency = str(
            input("Enter set_fsr_frequency of the RF Amp: "))
        return set_fsr_frequency
    if val == "set_Power":
        set_rf_dB_level = str((input("Enter set_rf_dB_level of the RF Amp: ")))
        return set_rf_dB_level
    if val == "OnOffState":
        set_on_off_state = str(input("Enter RF Amp set_on_off_state Number: "))
        return set_on_off_state
    if val == "Id":
        Id = int(input("Enter Id of RF Amp: "))
        return Id


def create_RFAmp():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        section_id = form.getvalue("section_id")
        set_Frequency = form.getvalue("set_fsr_frequency")
        set_Power = form.getvalue("set_Power")
        OnOffState = form.getvalue("OnOffState")

    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        section_id = form_getvalue("section_id")
        set_Frequency = form_getvalue("set_fsr_frequency")
        set_Power = form_getvalue("set_Power")
        OnOffState = form_getvalue("OnOffState")

    query = c.execute("select count(*) from RF_Amp where name='"+name+"'")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=rf_amp,args=7,uuid={0},action={1},element_name={2},state={3},section_id={4},set_fsr_frequency={5},set_rf_dB_level={6},set_on_off_state={7},device={8}"\
                .format(cmd_id, cmd, name, state, section_id, set_fsr_frequency, set_rf_dB_level, set_on_off_state, 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", "section_id": "Name Already exists"})))

    else:
        if (nameCount == 0):
            query = c.execute("insert into rf_amp(name,state,section_id,set_fsr_frequency,set_rf_dB_level,set_on_off_state,cr_date) values(?,?,?,?,?,?,datetime())", [
                              name, state, section_id, set_fsr_frequency, set_rf_dB_level, set_on_off_state])
            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_RFAmp():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        id = form.getvalue("id")
        name = form.getvalue("name")
        state = form.getvalue("state")
        section_id = form.getvalue("section_id")

        set_Power = form.getvalue("set_Power")
        set_Frequency = form.getvalue("set_Frequency")
        OnOffState = form.getvalue("OnOffState")

    else:
        id = form_getvalue("Id")
        name = form_getvalue("name")
        state = form_getvalue("state")
        section_id = form_getvalue("section_id")
        set_Frequency = form_getvalue("set_fsr_frequency")
        set_Power = form_getvalue("set_Power")
        OnOffState = form_getvalue("OnOffState")

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

    if (CCM == true):
        if (nameCount > 0):
            c.execute("select name,state,section_id,id from rf_amp")
            for col in c:
                name = col[0]
                state = col[1]
                section_id = col[2]
                #id = col[3]

            # message = "set,element=rf_amp,args=7,uuid={0},action={1},element_name={2},state={3},section_id={4},set_fsr_frequency={5},set_rf_dB_level={6},set_on_off_state={7},id={8},device={9}"\
            # .format(cmd_id,cmd,name,state,section_id,set_fsr_frequency,set_rf_dB_level,set_on_off_state,id,device)
            message = "set,element=rf_amp,args=7,uuid={0},action={1},element_name={2},state={3},section_id={4},set_fsr_frequency={5},set_rf_dB_level={6},set_on_off_state={7},id={8},device={9}"\
                .format(cmd_id, cmd, name, state, section_id, set_Frequency, set_Power, OnOffState, 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 rf_amp set set_fsr_frequency=?,set_rf_dB_level=?,set_on_off_state=?,edit_date=datetime() where id=?",
                              [set_Frequency, set_Power, 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()


def delete_RFAmp():

    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("Id")
        name = form.getvalue("name")
    else:
        name = form_getvalue("name")
        id = form_getvalue("Id")

    if (CCM == true):
        message = "set,element=rf_amp,args=7,uuid={0},action={1},element_name={2},id={3},device={4}".format(
            cmd_id, cmd, name, id, 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 rf_amp where id="+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_RFAmp():
    if(GUI == true):
        id = form.getvalue("Id")
        name = form.getvalue("name")
    else:
        name = form_getvalue("name")
        id = form_getvalue("Id")

    query = c.execute("select id,name,state,section_id,set_min_fsr_frequency,set_max_fsr_frequency,ifnull(set_fsr_frequency,set_min_fsr_frequency),set_min_rf_dB_level,set_max_rf_dB_level,ifnull(set_rf_dB_level,set_min_rf_dB_level),set_on_off_state,get_rf_dB_level from rf_amp")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "name": col[1], "state": col[2], "section_id": col[3], "min_Frequency": col[4], "max_Freqency": col[5],
                      "set_Frequency": col[6], "min_Power": col[7], "max_Power": col[8], "set_Power": col[9], "OnOffState": col[10] == 1, "getPower": col[11]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:text/html\r\n\r\n")
if(request_Type == 'create_RFAmp'):
    create_RFAmp()
elif(request_Type == 'update_RFAmp'):
    update_RFAmp()
elif(request_Type == 'delete_RFAmp'):
    delete_RFAmp()
else:
    read_RFAmp()
