#!/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 state FROM ip_cfg UNION ALL SELECT state FROM remote_control UNION ALL select state from TEC")

    for col in c:
        dbData.append(col[0])
    # 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"] = [{"status" : 1, "name": "TEC 1 Temperature"}, {"status": 1, "name":"TEC 1 Current"}, {"status": 1, "name": "TEC 2 Temperature"}, {"status": 0, "name":"TEC 2 Current"}]
    # 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_currentSettingsNGP():
    cmd = "read"
    #cmd_id = get_ccm_command_id()

    jsonSchema = {}
    dbData = []

    # ModeMap

    query = c.execute("select set_wavelength,set_min_smsr,10,10 from mode_map")
    for col in c:
        jsonSchema = {"waveLength": col[0], "smsr": col[1],
                      "dataRate": col[2], "outPutPower": col[3]}

    # Section:

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

    for col in c:
        secName = col[0]
        i_drive_id = col[1]
        if i_drive_id != None:
            secNames.append(secName)
            iDrives.append(i_drive_id)
        else:
            pass

    for i in range(len(iDrives)):
        sectionIndex = secNames.index(secNames[i])
        sectionName = secNames[i].split("-")[1]
        if sectionName.startswith("Slave") or sectionName.startswith("Master"):
            if sectionName.startswith("Slave"):
                sectionName = "Slave"
                c.execute("select state from i_drive where id ='" +
                          str(iDrives[sectionIndex])+"'")
                currControlState = c.fetchone()[0]
                slvDrives.append(currControlState)
            else:
                sectionName = "Master"
                c.execute("select state from i_drive where id ='" +
                          str(iDrives[sectionIndex])+"'")
                currControlState = c.fetchone()[0]
                masterDrives.append(currControlState)

        else:
            c.execute("select state from i_drive where id ='" +
                      str(iDrives[sectionIndex])+"'")
            currControlState = c.fetchone()[0]
            jsonSchema[sectionName] = currControlState

    jsonSchema["Slave"] = max(slvDrives)
    jsonSchema["Master"] = max(masterDrives)

    # Values needs to be
    jsonSchema.update(defaultStatus())
    jsonSchema.update({"Date Modulation": 1})
    print(json.JSONEncoder().encode(jsonSchema))


def read_currentSettingsLYRATL():

    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 set_wavelength,set_power from mode_map where id in "+(id))
    query = c.fetchall()
    array = []
    for col in query:
        array.append(col[0])
        array.append(0 if  col[1] is None else col[1])
        # JS['wavelength'] = col[0]
        # JS['FSR'] = col[1]
    JS["laser_data"] = 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": [],"Slave" : [{"status" : 1, "name":"Laser 1 Bias Current"},{"status": 0, "name": "Laser 1 Optical  Power"}, {"status": 1, "name":"Laser 1 Etalon"},{"status": 0,"name": "Laser 1 Frequency Meter"}, {"status": 0, "name": "Laser 2 Bias Current"}, {"status": 1, "name": "Laser 2 Optical  Power"}, {"status": 1,"name":"Laser 2 Etalon"}, {"status": 1, "name": "Laser 2 Frequency Meter"}]})
    print(json.JSONEncoder().encode(JS))


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

    jsonSchema = {}
    dbData = []

    # ModeMap

    query = c.execute(
        "select set_wavelength,set_min_smsr,set_power from mode_map")
    for col in c:
        jsonSchema = {
            "CentralWaveLength": col[0], "smsr": col[1], "OutputPower": col[2]}

    # Section:

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

    for col in c:
        secName = col[0]
        i_drive_id = col[1]
        if i_drive_id != None:
            secNames.append(secName)
            iDrives.append(i_drive_id)
        else:
            pass

    for i in range(len(iDrives)):
        sectionIndex = secNames.index(secNames[i])
        sectionName = secNames[i].split("-")[1]
        c.execute("select state from i_drive where id ='" +
                  str(iDrives[sectionIndex])+"'")
        currControlState = c.fetchone()[0]
        jsonSchema[sectionName] = currControlState

    jsonSchema.update(defaultStatus())

    # Values needs to be
    jsonSchema.update({"RF Synthesizer": 1, "RF Power On": 1})
    print(json.JSONEncoder().encode(jsonSchema))


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

    jsonSchema = {}
    dbData = []

    query = c.execute(
        "select set_central_wavelength,set_comb_FSR from comb_map")
    for col in c:
        jsonSchema = {"waveLength": col[0], "pulse_repetition": col[1]}

    # Section:

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

    for col in c:
        secName = col[0]
        i_drive_id = col[1]
        if i_drive_id != None:
            secNames.append(secName)
            iDrives.append(i_drive_id)
        else:
            pass

    for i in range(len(iDrives)):
        sectionIndex = secNames.index(secNames[i])
        sectionName = secNames[i].split("-")[1]
        if sectionName.startswith("Slave") or sectionName.startswith("Master"):
            if sectionName.startswith("Slave"):
                sectionName = "Slave"
                c.execute("select state from i_drive where id ='" +
                          str(iDrives[sectionIndex])+"'")
                currControlState = c.fetchone()[0]
                slvDrives.append(currControlState)
            else:
                sectionName = "Master"
                c.execute("select state from i_drive where id ='" +
                          str(iDrives[sectionIndex])+"'")
                currControlState = c.fetchone()[0]
                masterDrives.append(currControlState)

        else:
            c.execute("select state from i_drive where id ='" +
                      str(iDrives[sectionIndex])+"'")
            currControlState = c.fetchone()[0]
            jsonSchema[sectionName] = currControlState

    jsonSchema["Slave"] = max(slvDrives)
    jsonSchema["Master"] = max(masterDrives)

    # Values needs to be
    jsonSchema.update(defaultStatus())
    jsonSchema.update({"RF Synthesizer": 1, "RF Power On": 1})
    print(json.JSONEncoder().encode(jsonSchema))


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

    jsonSchema = {}
    dbData = []

    # ModeMap

    query = c.execute(
        "select set_wavelength,set_min_smsr,set_power from mode_map")
    for col in c:
        jsonSchema = {
            "CentralWaveLength": col[0], "smsr": col[1], "OutputPower": col[2]}

    # Section:

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

    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("-")[0]
        c.execute("select state from i_drive where id ='" +
                  str(iDrives[sectionIndex])+"'")
        currControlState = c.fetchone()[0]
        jsonSchema[sectionName] = currControlState

    jsonSchema.update(defaultStatus())

    # jsonSchema.update({"Temperature":1,"PowerSupply":1,"Fan":1})
    print(json.JSONEncoder().encode(jsonSchema))


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

    jsonSchema = {}
    dbData = []

    # ModeMap

    query = c.execute(
        "select set_central_wavelength,set_comb_FSR from comb_map")
    query = c.fetchall()
    for col in query:
        jsonSchema['wavelength'] = col[0]
        jsonSchema['FSR'] = col[1]
    # Section:

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

    for col in c:
        secName = col[0]
        i_drive_id = col[1]
        if i_drive_id != None:
            secNames.append(secName)
            iDrives.append(i_drive_id)
        else:
            pass
   # print "SectionNames",secNames
    # print "iDrives",iDrives

    for i in range(len(iDrives)):
        # print "SecName[i]",secNames[i]
        sectionIndex = secNames.index(secNames[i])
        sectionName = secNames[i].split("-")[1]
        # print "SectionName",secName
        if sectionName.startswith("SLV") or sectionName.startswith("NLW") or sectionName.startswith("TL"):
            if sectionName.startswith("SLV"):
                sectionName = "Slave"
                c.execute("select state from i_drive where id ='" +
                          str(iDrives[sectionIndex])+"'")
                currControlState = c.fetchone()[0]
                jsonSchema["Slave"] = currControlState
            else:
                sectionName = "Master"
                c.execute("select state from i_drive where id ='" +
                          str(iDrives[sectionIndex])+"'")
                currControlState = c.fetchone()[0]
                jsonSchema["Master"] = currControlState

        else:
            c.execute("select state from i_drive where id ='" +
                      str(iDrives[sectionIndex])+"'")
            currControlState = c.fetchone()[0]
            jsonSchema[sectionName] = currControlState

    jsonSchema.update(defaultStatus())

    jsonSchema.update({"RF Synthesizer": 1, "RF Power On": 1})
    print(json.JSONEncoder().encode(jsonSchema))

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_currentSettingsNGP'):
    read_currentSettingsNGP()
elif(request_Type == 'read_currentSettingsLYRATL'):
    read_currentSettingsLYRATL()
elif(request_Type == 'read_currentSettingsSML'):
    read_currentSettingsSML()
elif(request_Type == 'read_currentSettingsOCS2000'):
    read_currentSettingsOCS2000()
elif(request_Type == 'read_GenericDevice'):
    read_GenericDevice()
elif(request_Type == 'read_OCS_PPS_1000_1100'):
    read_OCS_PPS_1000_1100()
elif(request_Type == 'output'):
    output()
elif(request_Type == 'module'):
    module()
else:
    read_currentSettings()
