#!/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 RF Sweep")
    print("2.Update RF Sweep")
    print("3.Delete RF Sweep")
    print("4.Read RF Sweep")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_RFSweep'
    elif choice == 2:
        request_Type = 'update_RFSweep'
    elif choice == 3:
        request_Type = 'delete_RFSweep'
    elif choice == 4:
        request_Type = 'read_RFSweep'
    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 Sweep: "))
        return name
    if val == "state":
        state = str(input("Enter state of the RF Sweep: "))
        return state
    if val == "rf_amp_id":
        rf_amp_id = str(input("Enter rf_amp_id:"))
        return rf_amp_id
    if val == "set_min_frequency":
        set_min_frequency = str(
            input("Enter set_min_frequency of the RF Sweep: "))
        return set_min_frequency
    if val == "set_max_frequency":
        set_max_frequency = str(
            (input("Enter set_max_frequency of the RF Sweep: ")))
        return set_max_frequency
    if val == "set_dead_band":
        set_dead_band = str(input("Enter RF Sweep set_dead_band NUmber: "))
        return set_dead_band
    if val == "Id":
        Id = int(input("Enter Id: "))
        return Id
    if val == "set_sweep_freq":
        set_freq = str(input("Enter Set_Sweep_frequency: "))
        return set_freq


def create_RFSweep():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    print("Create")
    if(GUI == true):
        name = form.getvalue("name")
        state = form.getvalue("state")
        rf_amp_id = form.getvalue("rf_amp_id")
        set_min_frequency = form.getvalue("set_min_frequency")
        set_max_frequency = form.getvalue("set_max_frequency")
        set_dead_band = form.getvalue("set_dead_band")
        set_sweep_freq = form.getvalue("set_sweep_freq")

    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        rf_amp_id = form_getvalue("rf_amp_id")
        set_min_frequency = form_getvalue("set_min_frequency")
        set_max_frequency = form_getvalue("set_max_frequency")
        set_dead_band = form_getvalue("set_dead_band")
        set_sweep_freq = form_getvalue("set_sweep_freq")

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

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=rf_sweep,args=8,uuid={0},action={1},element_name={2},state={3},rf_amp_id={4},set_min_frequency={5},set_max_frequency={6},set_sweep_freq={7},set_dead_band={8},device={9}"\
                .format(cmd_id, cmd, name, state, rf_amp_id, set_min_frequency, set_max_frequency, set_sweep_freq, set_dead_band, 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 rf_sweep(name,state,rf_amp_id,set_min_frequency,set_max_frequency,set_dead_band,set_sweep_freq,cr_date) values(?,?,?,?,?,?,?,datetime())", [
                              name, state, rf_amp_id, set_min_frequency, set_max_frequency, set_dead_band, set_sweep_freq])
            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_RFSweep():
    cmd = "update"
    cmd_id = get_ccm_command_id()

    if(GUI == true):
        id = form.getvalue("Id")
        name = form.getvalue("name")
        state = form.getvalue("state")
        rf_amp_id = form.getvalue("rf_amp_id")
        set_min_frequency = form.getvalue("set_min_frequency")
        set_max_frequency = form.getvalue("set_max_frequency")
        set_dead_band = form.getvalue("set_dead_band")
        set_sweep_freq = form.getvalue("set_sweep_freq")

    else:
        Id = form_getvalue("Id")
        name = form_getvalue("name")
        state = form_getvalue("state")
        rf_amp_id = form_getvalue("rf_amp_id")
        set_min_frequency = form_getvalue("set_min_frequency")
        set_max_frequency = form_getvalue("set_max_frequency")
        set_dead_band = form_getvalue("set_dead_band")
        set_sweep_freq = form_getvalue("set_sweep_freq")

    query = c.execute(
        "select count(*) from rf_sweep where name=? and id not like ?", [name, Id])
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if (nameCount == 0):
            message = "set,element=rf_sweep,args=9,uuid={0},action={1},element_name={2},state={3},rf_amp_id={4},set_min_frequency={5},set_max_frequency={6},set_dead_band={7},set_sweep_freq={8},id={9},device={10}"\
                .format(cmd_id, cmd, name, state, rf_amp_id, set_min_frequency, set_max_frequency, set_dead_band, set_sweep_freq, 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_sweep set name=?,state=?,rf_amp_id=?,set_min_frequency=?,set_max_frequency=?,set_dead_band=?,set_sweep_freq=?,edit_date=datetime() where id=?",
                              [name, state, rf_amp_id, set_min_frequency, set_max_frequency, set_dead_band, set_sweep_freq, 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_RFSweep():

    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_sweep,args=4,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_sweep 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_RFSweep():
    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,rf_amp_id,set_min_frequency,set_max_frequency,set_dead_band,set_sweep_freq from rf_sweep where id="+str(Id)+"")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0], "name": col[1], "state": col[2], "rf_amp_id": col[3],
                      "set_min_frequency": col[4], "set_max_frequency": col[5], "set_dead_band": col[6], "set_sweep_freq": col[7]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == 'create_RFSweep'):
    create_RFSweep()
elif(request_Type == 'update_RFSweep'):
    update_RFSweep()
elif(request_Type == 'delete_RFSweep'):
    delete_RFSweep()
else:
    read_RFSweep()
