#!/usr/bin/python3

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


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

device=DeviceName
dbFileName = DBPath.split("/")[-1]
#print dbFileName

if (GUI==true):
    form = cgi.FieldStorage()
    request_Type = form.getvalue("requestType")
else:
    print("1.Create TEC")
    print("2.Read TEC")
    print("3.Update TEC")
    print("4.Delete TEC")
    choice = int(input("Enter cgi Function: "))
    if choice == 1:
        request_Type = "create_TEC"
    elif choice == 2:
        request_Type = "read_TEC"
    elif choice == 3:
        request_Type = "update_TEC"
    elif choice == 4:
        request_Type = "delete_TEC"
    else:
        print ("Enter a valid choice ")
    print("Request Type ",str(request_Type))

def form_getvalue(val):
    if val == "Id":
        tecId = int(input("Enter TEC ID: "))
        return tecId
    elif val == "name":
        tecName = str(input("Enter TEC Name: "))
        return tecName
    elif val == "state":
        tecState = int(input("Enter TEC State: "))
        return tecState
    elif val == "pic_Id":
        tecPicId = int(input("Enter pic Id: "))
        return tecPicId
    elif val == "setMaxTemp":
        tecMaxTemp = str(input("Enter Max Temp: "))
        return tecMaxTemp
    elif val == "setMinTemp":
        tecMinTemp = str(input("Enter Min Temp: "))
        return tecMinTemp
    elif val == "setTemp":
        tecSetTemp = str(input("Enter Temp: "))
        return tecSetTemp
    elif val == "getTemp":
        tecGetTemp = str(input("Get Temp: "))
        return tecGetTemp
    elif val == "setCurrentLimit":
        tecSetCurrent = str(input("Set Current Limit: "))
        return tecSetCurrent
    elif val == "getCurrentLimit":
        tecGetCurrent = str(input("Get Current Limit: "))
        return tecGetCurrent
    elif val == "getAmbTemp":
        tecAmbientTemp = str(input("Get Ambient Temperature: "))
        return tecAmbientTemp
    elif val == "onOffState":
        tecOnOffState = str(input("Get set On off State: "))
        return tecOnOffState


    else:
        pass



def create_TEC():
    #print "Create TEC"

    cmd = "create"
    cmd_id = get_ccm_command_id()
    if(GUI==true):
        tecName = form.getvalue("name")
        tecState =0 #form.getvalue("state")
        tecPicId = form.getvalue("pic_Id")
        tecMaxTemp = form.getvalue("setMaxTemp")
        tecMinTemp = form.getvalue("setMinTemp")
        tecSetTemp = form.getvalue("setTemp")
        tecGetTemp = form.getvalue("getTemp")
        tecSetCurrent = form.getvalue("setCurrentLimit")
        tecGetCurrent = form.getvalue("getCurrentLimit")
        tecAmbientTemp = form.getvalue("getAmbTemp")
        tecOnOffState = form.getvalue("onOffState")
    else:
        tecName = form_getvalue("name")
        tecState = 0#form_getvalue("state")
        tecPicId = form_getvalue("pic_Id")
        tecMaxTemp = form_getvalue("setMaxTemp")
        tecMinTemp = form_getvalue("setMinTemp")
        tecSetTemp = form_getvalue("setTemp")
        tecGetTemp = form_getvalue("getTemp")
        tecSetCurrent = form_getvalue("setCurrentLimit")
        tecGetCurrent = form_getvalue("getCurrentLimit")
        tecAmbientTemp = form_getvalue("getAmbTemp")
        tecOnOffState = form_getvalue("onOffState")

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

        if(CCM == true):
            message = "set,element=TEC,args=12,,uuid={0},action={1},element_name={2},state={3},picId={4},maxTmp={5},minTmp={6},setTmp={7},getTmp={8},setCrntLt={9},getCrntLt={10},getAmbTmp={11},setOnOffState={12},device={13}".\
            format(cmd_id,cmd,tecName,tecState,tecPicId,tecMaxTemp,tecMinTemp,tecSetTemp,tecGetTemp,tecSetCurrent,tecGetCurrent,tecAmbientTemp,tecOnOffState,device)
            #send_ccm_msg(message)
            send_ccm_msg(message)
            response = get_ccm_response(cmd_id)
            print(response)
            delete_ccm_response(cmd_id)
        else:
            try:
                query = c.execute("""insert into TEC(name,state,pic_id,set_max_temp,set_min_temp,set_temp,get_temp,
                    set_TEC_current_limit,get_TEC_current,get_ambient_temp,cr_date,edit_date) values
                    (?,?,?,?,?,?,?,?,?,?,datetime(),datetime()) """,
                    [tecName,tecState,tecPicId,tecMaxTemp,tecMinTemp,tecSetTemp,tecGetTemp,tecSetCurrent,tecGetCurrent,tecAmbientTemp])
                conn.commit()
                print((json.JSONEncoder().encode({"status":"success","description":"Successfully Created"})))
            except Exception as e:
                print((json.JSONEncoder().encode({"status":"fail","description":e})))
    else:
        print((json.JSONEncoder().encode({"status":"fail","description":"Name already Exists"})))

    c.close()
    conn.close()

def update_TEC():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    if(GUI==true):
        tecName = form.getvalue("name")
        tecState = 1 #form.getvalue("state")
        tecSetTemp = form.getvalue("set_current")
        tecOnOffState = form.getvalue("set_on_off_state")

        #FACTORY SETTINGS
        tecPicId = form.getvalue("pic_Id") 
        tecMaxTemp = form.getvalue("setMaxTemp")
        tecMinTemp = form.getvalue("setMinTemp")        
        tecGetTemp = form.getvalue("getTemp")
        tecSetCurrent = form.getvalue("setCurrentLimit")
        tecGetCurrent = form.getvalue("getCurrentLimit")
        tecAmbientTemp = form.getvalue("getAmbTemp")
        tecId = form.getvalue("id")
        tecSetWavelength = form.getvalue("tecSetWavelength")
        
        
    else:
        tecName = form_getvalue("name")
        tecState = form_getvalue("state")
        tecPicId = form_getvalue("pic_Id")
        tecMaxTemp = form_getvalue("setMaxTemp")
        tecMinTemp = form_getvalue("setMinTemp")
        tecSetTemp = form_getvalue("setTemp")
        tecGetTemp = form_getvalue("getTemp")
        tecSetCurrent = form_getvalue("setCurrentLimit")
        tecGetCurrent = form_getvalue("getCurrentLimit")
        tecAmbientTemp = form_getvalue("getAmbTemp")
        tecId = form_getvalue("Id")
        tecOnOffState = form_getvalue("onOffState")

    query = c.execute("select count(*) from TEC")
    nameCount = c.fetchone()[0]
    if nameCount > 0:
        if (CCM == true):
            c.execute("select id,name,state,pic_id,set_max_temp,set_min_temp,get_temp,set_TEC_current_limit,get_TEC_current,set_min_wavelength,set_max_wavelength from TEC where id= '"+tecId+"'")
            for col in c:
                #tecId = col[0]
                tecName = col[1]
                tecState = col[2]
                tecPicId = col[3]
                tecMaxTemp = col[4]
                tecMinTemp = col[5]
                tecGetTemp = col[6]
                tecSetCurrent = col[7]
                tecGetCurrent = col[8]
                tecMinWave = col[9]
                tecMaxWave = col[10]
            
            message = "set,element=TEC,args=13,uuid={0},action={1},element_name={2},state={3},picId={4},maxTmp={5},minTmp={6},setTmp={7},getTmp={8},setCrntLt={9},getCrntLt={10},Id={11},setOnOffState={12},minWavelength={13},maxWavelength={14},setWavelength={15},device={16}".\
            format(cmd_id,cmd,tecName,tecState,tecPicId,tecMaxTemp,tecMinTemp,tecSetTemp,tecGetTemp,tecSetCurrent,tecGetCurrent,tecId,tecOnOffState,tecMinWave,tecMaxWave,tecSetWavelength,device)
        
            send_ccm_msg(message)
            response = get_ccm_response(cmd_id)
            print(response)
            delete_ccm_response(cmd_id)
        else:
            try:
                query = c.execute("update TEC set set_on_off_state=?,set_temp=?,set_wavelength=?,edit_date=datetime() where id=?",[tecOnOffState,tecSetTemp,tecSetWavelength,tecId])
                conn.commit()
                print(json.JSONEncoder().encode({"status":"success","description":"Successfully Updated"}))
            except Exception as e:
                print(json.JSONEncoder().encode({"status":"fail","description":str(e)}))

    else:
        print(json.JSONEncoder().encode({"status":"fail","description":"Name Alreadt Exists"}))
    c.close()
    conn.close()


def read_TEC():
    if(GUI==true):
        tecId = form.getvalue("Id")
        tecName = form.getvalue("name")
    else:
        tecId = form_getvalue("Id")
        tecName = form_getvalue("name")

    try:
        query = c.execute("select id,name,state,pic_id, set_max_temp,set_min_temp,ifnull(set_temp,set_min_temp),get_temp,set_TEC_current_limit,get_TEC_current,get_ambient_temp,set_on_off_state,set_min_wavelength,set_max_wavelength,set_wavelength from TEC")
        conn.commit()
        dbData = []
        for col in c:
            json_schema={"Id":col[0],"name":col[1],"state":col[2],"picId":col[3],"setMaxTemp":col[4],"setMinTemp":col[5],"setTemp":col[6],"getTemp":col[7],"setCurrentLt":col[8],"getCurrent":col[9],"getAmbTemp":col[10],"onOffState":col[11],"minWavelength":col[12],"maxWavelength":col[13],"setWavelength":col[14]}
            dbData.append(json_schema)
        print(json.JSONEncoder().encode(dbData))
    except Exception as e:
        print(json.JSONEncoder().encode({"status":"fail","description":str(e)}))
    finally:
        c.close()
        conn.close()

def delete_TEC():
    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if (GUI==true):
        tecId = form.getvalue("Id")
        tecName = form.getvalue("name")
    else:
        tecId = form_getvalue("Id")
        tecName = form_getvalue("name")

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





def read_PIC():
    #query = c.execute("select id,name,state,features,system_id from PIC where id='"+picId+"'")
    query = c.execute("select id,name from PIC")
    dbData=[]
    conn.commit()
    for col in c:
        jsonSchema = {"Id":col[0],"Name":col[1]}
        dbData.append(jsonSchema)
        print((json.JSONEncoder().encode(jsonSchema)))



print("Content-Type:text/html\r\n\r\n")
if request_Type=="create_TEC":
    create_TEC()
elif request_Type == "update_TEC":
    update_TEC()
elif request_Type == "delete_TEC":
    delete_TEC()
else:
    read_TEC()
#else:
#   read_PIC()

