#!/usr/bin/python3

import json
from db import *
from globalSettings import *
from global_func import *
import sqlite3
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 Features")
    print("2.Read Features")
    print("3.Update Features")
    print("4.Delete Features")
    choice = int(input("Select Cgi Function"))
    if choice == 1:
        request_Type = "create_Features"
    elif choice == 2:
        request_Type = "read_Features"
    elif choice == 3:
        request_Type = "update_Features"
    elif choice == 4:
        request_Type = "delete_Features"
    else:
        print("Enter Valid Choice")
    print(("Request Type:", str(request_Type)))


def form_getvalue(val):
    if val == "Id":
        featId = int(input("Enter Features id: "))
        return featId

    elif val == "VOA":
        featVOA = str(input("Enter VOA: "))
        return featVOA

    elif val == "laser":
        featLaser = int(input("Enter laser: "))
        return featLaser

    elif val == "MMI":
        featMMI = int(input("Enter MMI: "))
        return featMMI

    elif val == "SOA":
        featSOA = int(input("Enter SOA: "))
        return featSOA

    elif val == "coupler":
        featCoupler = int(input("Enter Coupler: "))
        return featCoupler

    elif val == "demux":
        featDemux = int(input("Enter Demux: "))
        return featDemux

    elif val == "modulator":
        featModulator = int(input("Enter Modulator: "))
        return featModulator

    elif val == "comb":
        featComb = int(input("Enter COMB: "))
        return featComb

    else:
        pass


def create_Features():
    print("create_Features")
    cmd = "create"
    cmd_id = get_ccm_command_id()

    if (GUI == true):
        #featId = form.getvalue("Id")
        featVOA = form.getvalue("VOA")
        featLaser = form.getvalue("laser")
        featMMI = form.getvalue("MMI")
        featSOA = form.getvalue("SOA")
        featCoupler = form.getvalue("coupler")
        featDemux = form.getvalue("demux")
        featModulator = form.getvalue("modulator")
        featComb = form.getvalue("comb")

    else:

        #featId = form_getvalue("Id")
        featVOA = form_getvalue("VOA")
        featLaser = form_getvalue("laser")
        featMMI = form_getvalue("MMI")
        featSOA = form_getvalue("SOA")
        featCoupler = form_getvalue("coupler")
        featDemux = form_getvalue("demux")
        featModulator = form_getvalue("modulator")
        featComb = form_getvalue("comb")

    if (CCM == true):
        message = "set,element=features,args=9,action={0},voa={1},laser={2},mmi={3},soa={4},coupler={5},demux={6},modulator={7},comb={8},uuid={9},device={10}".format(
            cmd, featVOA, featLaser, featMMI, featSOA, featCoupler, featDemux, featModulator, featComb, cmd_id, device)

        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        try:
            query = c.execute("insert into features(VOA,laser,SOA,MMI,coupler,demux,modulator,comb) values(?,?,?,?,?,?,?,?)",
                              [featVOA, featLaser, featSOA, featMMI, featCoupler, featDemux, featModulator, featComb])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Saved"})))
        except Exception as e:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Failed to Save"})))

    c.close()
    conn.close()


def read_Features():
    cmd = "read"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        featId = form.getvalue("Id")
    else:
        featId = form_getvalue("Id")

    try:
        query = c.execute(
            "select id,VOA,laser,SOA,MMI,coupler,demux,modulator,comb from features where id='"+str(featId)+"'")
        dbData = []
        for col in c:
            jsonres = {"id": col[0], "VOA": col[1], "laser": col[2], "SOA": col[3], "MMI": col[4], "coupler": col[5], "demux": col[6],
                       "modulator": col[7], "comb": col[8]}
            dbData.append(jsonres)
        print((json.JSONEncoder().encode(dbData)))

    except Exception as e:
        print((json.JSONEncoder().encode(e)))
    c.close()
    conn.close()


def update_Features():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    if (GUI == true):
        featId = form.getvalue("Id")
        featVOA = form.getvalue("VOA")
        featLaser = form.getvalue("laser")
        featMMI = form.getvalue("MMI")
        featSOA = form.getvalue("SOA")
        featCoupler = form.getvalue("coupler")
        featDemux = form.getvalue("demux")
        featModulator = form.getvalue("modulator")
        featComb = form.getvalue("comb")

    else:

        featId = form_getvalue("Id")
        featVOA = form_getvalue("VOA")
        featLaser = form_getvalue("laser")
        featMMI = form_getvalue("MMI")
        featSOA = form_getvalue("SOA")
        featCoupler = form_getvalue("coupler")
        featDemux = form_getvalue("demux")
        featModulator = form_getvalue("modulator")
        featComb = form_getvalue("comb")

    if (CCM == true):
        message = "set,element=features,args=10,action={0},voa={1},laser={2},mmi={3},soa={4},coupler={5},demux={6},modulator={7},comb={8},Id={9},uuid={10},device={11}".\
            format(cmd, featVOA, featLaser, featMMI, featSOA, featCoupler,
                   featDemux, featModulator, featComb, featId, cmd_id, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        try:
            c.execute("update features set VOA=?,laser=?,SOA=?,MMI=?,coupler=?,demux=?,modulator=?,comb=? where id=?",
                      [featVOA, featLaser, featSOA, featMMI, featCoupler, featDemux, featModulator, featComb, featId])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated"})))

        except Exception as e:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": e})))

    c.close()
    conn.close()


def delete_Features():
    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        featId = form.getvalue("Id")
    else:
        featId = form_getvalue("Id")

    if(CCM == true):
        message = "set,element=features,args=3,action={0},Id={1},uuid={2},device={3}".format(
            cmd, featId, cmd_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 features where id='"+featId+"'")
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "sucess", "description": "Successfully Deleted"})))
        except Exception as e:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Failed"})))
    c.close()
    conn.close()


print("Content-type:/text/html\r\n\r\n")
if(request_Type == "create_Features"):
    create_Features()
elif (request_Type == "update_Features"):
    update_Features()
elif (request_Type == "delete_Features"):
    delete_Features()
else:
    read_Features()
