#!/usr/bin/python3

import json
import sqlite3
from db import *
from globalSettings import *
from global_func import *
import cgi
import cgitb
cgitb.enable()

device = DeviceName
DBPath = DBPath  # "SML_2000DB.db"

conn = sqlite3.connect(DBPath)
conn.text_factory = str
c = conn.cursor()


#GUI = false

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

else:
    request_Type = "read_OCS_PPS_1000_1100"
    print("Reques_Type="+str(request_Type))


def defaultStatus():
    jsonSchema = {}
    dbData = []
    query = c.execute(
        "select id, state from TEC")

    for col in c:
        dbData.append({
            "name": f"TEC {col[0]}",
            "status": col[1]
        })

    # jsonSchema["ethernet"] = dbData[0]
    jsonSchema["ethernet"] = [{"status" :1 , "name": "IOPS RD"},{"status": 0, "name": "IOPS WR"},{"status" : 2 , "name": "MB RD"},{"status" : 1, "name":"MB WR"}]
    # jsonSchema["remote"] = dbData[1]
    # jsonSchema["remote"] = []
    # jsonSchema["tec"] = dbData[2]
    jsonSchema["tec"] = dbData
    # print jsonSchema

    jsonSchema.update({"Temperature": [{"status": 1, "name":"Temperature 1"}, {"status": 1, "name": "Temperature 2"}], "PowerSupply": [{"status": 1, "name":"AC"}, {"status": 1 , "name": "5V"}, {"status": 0, "name":"12V"}, {"status": 2,"name":"3V3"}, {"status": 1,"name": "6.2V"}], "Fan": [{"status": 1, "name" : "FAN1 RPM"}, {"status":2,"name":"FAN2 RPM"}]})

    return jsonSchema


def read_currentSettings():
    cmd = "read"
    #cmd_id = get_ccm_command_id()

    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = form_getvalue("id")
    query = c.execute("select set_wavelength,set_min_smsr,10,10 from mode_map")
    dbData = []
    for col in c:
        jsonSchema = {"waveLength": col[0], "smsr": col[1],
                      "dataRate": col[2], "outPutPower": col[3]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))


def read_currentSettingsAdoptionELS():

    cmd = "read"
    #cmd_id = get_ccm_command_id()

    JS = {}

    # Current_Settings

    #query=c.execute("SELECT name, tone || '-'||demux_point_lut.comb_central_wav as value FROM demux_map INNER JOIN demux_point_lut ON  demux_map.id=demux_point_lut.id")

    query = c.execute(
        "SELECT demux.name,lut.tone|| '-'||lut.comb_central_wav from demux_map demux INNER JOIN demux_point_lut lut ON  demux.id = lut.demux_id")
    query = c.fetchall()
    for col in query:
        JS[col[0]] = col[1]

    # CombMap
    # if(wavelengthRange == 'Lyra-TL-5'):
    #     id = "(3,4)"
    # else:
    #     id = "(1,2)"
    query = c.execute(
        "select id, set_current,state from i_drive")
    query = c.fetchall()
    array = []
    for col in query:
        array.append({
            "name": f"Laser{col[0]} Current",
            "wavelength": col[1],
            "status": col[2]
        })
        # array.append(0 if  col[1] is None else col[1])
        # JS['wavelength'] = col[0]
        # JS['FSR'] = col[1]
    JS["current_controller"] = array 

    # Section:

    secNames = []
    iDrives = []
    slvDrives = []
    masterDrives = []
    query = c.execute("select name,id from i_drive")

    for col in c:
        secNames.append(col[0])
        iDrives.append(col[1])

    if None in iDrives:
        indexval = iDrives.index(None)
        # print indexval
        secNames.remove(secNames[indexval])
        iDrives.remove(iDrives[indexval])
        # print name
        # print iDrives

    for i in range(len(iDrives)):
        sectionIndex = secNames.index(secNames[i])
        sectionName = secNames[i].split("-")[1]
        if sectionName.startswith("Slave"):
            sectionName = "Slave"
            c1 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%SlaveRef%" """))
            c1 = c.fetchall()
            c2 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%SlaveGain%" """))
            c2 = c.fetchall()

            if (c1[0][0] == 1 and c2[0][0] == 1):
                JS['Slave'] = 1

            elif (c1[0][0] == 0 and c2[0][0] == 0):
                JS['Slave'] = 0

            elif ((c1[0][0] == 1 and c2[0][0] == 0) or (c1[0][0] == 0 and c2[0][0] == 1)):
                JS['Slave'] = 2

        elif sectionName.startswith("Master"):
            sectionName = "Master"
            c3 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%MasterRef%" """))
            c3 = c.fetchall()
            c4 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%MasterGain%" """))
            c4 = c.fetchall()

            if (c3[0][0] == 1 and c4[0][0] == 1):
                JS['Master'] = 1

            elif (c3[0][0] == 0 and c4[0][0] == 0):
                JS['Master'] = 0

            elif ((c3[0][0] == 1 and c4[0][0] == 0) or (c3[0][0] == 0 and c4[0][0] == 1)):
                JS['Master'] = 0

        elif sectionName.startswith("VOA"):
            sectionName = "VOA"
            c5 = (c.execute("""select state from i_drive where name like "%VOA%" """))
            c5 = c.fetchall()

            if (c5[0][0] == 1):
                JS['VOA'] = 1
            elif(c5[0][0] == 0):
                JS['VOA'] = 0
            elif(c5[0][0] == 2):
                JS['VOA'] = 2

        elif sectionName.startswith("Coupler"):
            sectionName = "Coupler"
            c6 = (c.execute("""SELECT state FROM i_drive WHERE name like "%Coupler%" """))
            c6 = c.fetchall()

            if (c6[0][0] == 1):
                JS['Coupler'] = 1
            elif(c6[0][0] == 0):
                JS['Coupler'] = 1
            elif(c6[0][0] == 2):
                JS['Coupler'] = 2

        elif sectionName.startswith("Demux1Ref1"):
            sectionName = "Demux1"
            c7 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Ref1%" """))
            c7 = c.fetchall()
            c8 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Gain1%" """))
            c8 = c.fetchall()

            if (c7[0][0] == 1 and c8[0][0] == 1):
                JS['Demux Output 1'] = 1

            elif (c7[0][0] == 0 and c8[0][0] == 0):
                JS['Demux Output 1'] = 0

            elif ((c7[0][0] == 1 and c8[0][0] == 0) or (c7[0][0] == 0 and c8[0][0] == 1)):
                JS['Demux Output 1'] = 2

        elif sectionName.startswith("Demux1Ref2"):
            sectionName = "Demux2"
            c9 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Ref2%" """))
            c9 = c.fetchall()
            c10 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Gain2%" """))
            c10 = c.fetchall()

            if (c9[0][0] == 1 and c10[0][0] == 1):
                JS['Demux Output 2'] = 1

            elif (c9[0][0] == 0 and c10[0][0] == 0):
                JS['Demux Output 2'] = 0

            elif ((c9[0][0] == 1 and c10[0][0] == 0) or (c9[0][0] == 0 and c10[0][0] == 1)):
                JS['Demux Output 2'] = 2

        elif sectionName.startswith("Demux1Ref3"):
            sectionName = "Demux3"
            c11 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Ref3%" """))
            c11 = c.fetchall()
            c12 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Gain3%" """))
            c12 = c.fetchall()

            if (c11[0][0] == 1 and c12[0][0] == 1):
                JS['Demux Output 3'] = 1

            elif (c11[0][0] == 0 and c12[0][0] == 0):
                JS['Demux Output 3'] = 0

            elif ((c11[0][0] == 1 and c12[0][0] == 0) or (c11[0][0] == 0 and c12[0][0] == 1)):
                JS['Demux Output 3'] = 2

        elif sectionName.startswith("Demux1Ref4"):
            sectionName = "Demux4"
            c13 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Ref4%" """))
            c13 = c.fetchall()
            c14 = (
                c.execute("""SELECT state FROM i_drive WHERE name like "%Demux1Gain4%" """))
            c14 = c.fetchall()

            if (c13[0][0] == 1 and c14[0][0] == 1):
                JS['Demux Output 4'] = 1

            elif (c13[0][0] == 0 and c14[0][0] == 0):
                JS['Demux Output 4'] = 0

            elif ((c13[0][0] == 1 and c14[0][0] == 0) or (c13[0][0] == 0 and c14[0][0] == 1)):
                JS['Demux Output 4'] = 2
    JS.update(defaultStatus())

    # JS.update({"RF Synthesizer": [],})
    print(json.JSONEncoder().encode(JS))




def output():
    print(json.JSONEncoder().encode({"status":200,"message":"Updated Successfully!"}))
def module():
    print(json.JSONEncoder().encode({"status":200,"message":"Updated Successfully!"}))

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

if(request_Type == 'read_currentSettingsAdoptionELS'):
    read_currentSettingsAdoptionELS()
elif(request_Type == 'output'):
    output()
elif(request_Type == 'module'):
    module()
else:
    read_currentSettings()
