#!/usr/bin/python3
import cgi,cgitb
import sqlite3
import time
import json
from global_func import *



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

cgitb.enable()
form = cgi.FieldStorage()
request_Type = form.getvalue('requestType')

def get_idacs():
    c.execute("select name,control_sectionName,state,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from i_dac")
    iDacData = []
    iDacName=[]
    for col in c:
        jsonSchema = {"name": col[0],"control_sectionName":col[1], "state": col[2], "set_on_off_state": col[3], "set_current_limit": col[4],
                      "set_min_current": col[5], "set_current": col[6], "get_current": col[7], "get_hardware_id": col[8], "id": col[9]}
        iDacData.append(jsonSchema)
    
    #dbData = {"i_dac_data": iDacData, "v_dac_data": vDacData}
    print(json.JSONEncoder().encode(iDacData))
def get_vdacs():
    c.execute("select name,id from v_dac limit 10")
    iDacData = []
    iDacName=[]
    for col in c:
        jsonSchema = {"name": col[0], "id": col[1]}
        iDacData.append(jsonSchema)
    
    #dbData = {"i_dac_data": iDacData, "v_dac_data": vDacData}
    print(json.JSONEncoder().encode(iDacData))

def Set_InstantaneousCurrent():
    # idac_data = form.getvalue("idac_data")
    # idac_data=[{'id': 1, 'label_name': 'P1-DCS1',
    #             'start_current':'10','stop_current':'50','increment_step':'0.5','interval_sec':'2',                
    #             "name":"username1","idac_max":"300"}]
    
    # data = idac_data[0]
    
    start_current = float(form.getvalue("start_current"))
    stop_current = float(form.getvalue("stop_current"))
    increment_step = float(form.getvalue("increment_step"))
    interval_sec = float(form.getvalue("interval_sec"))
    id = form.getvalue("id")
    device_type = form.getvalue("type")
    
    if device_type == 'iDAC':
        
        device_type ="i_dac"
        c.execute("select name from i_dac where id ='"+id+"'")
        for col in c:
            name = col[0]
            
        if (CCM == true):
            cmd = "create"
            cmd_id = get_ccm_command_id()
            action="create"
            # name="sweep"
            message = "set,element=sweep,args=9,uuid={0},action={1},element_name={2},start_current={3},stop_current={4},increment_step={5},interval_sec={6},id={7},device_type={8},device={9}"\
                    .format(cmd_id, cmd, name, start_current, stop_current, increment_step,interval_sec,id,device_type,device)

            send_ccm_msg(message)
            response = get_ccm_response(cmd_id)
            print(response)
            delete_ccm_response(cmd_id)
        else:
            c.execute("SELECT count(*)from sweep where iDAC_id = '"+id+"'")
            conn.commit()
            for col in c:
                count = col[0]
                
                
            if count == 0:
                c.execute("Insert into sweep (iDAC_id,start_current,stop_current,increment_step,increment_interval) values(?,?,?,?,?)",[id,start_current,stop_current,increment_step,interval_sec])
                conn.commit()
                print(json.JSONEncoder().encode(
                    {"status": "success", "description": "Successfully Created"}))
            else:
                
                c.execute("update sweep set start_current = ?, stop_current = ?,increment_step = ?,increment_interval = ? where iDAC_id = ?",[start_current,stop_current,increment_step,interval_sec,id])
                conn.commit()
                print(json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated"}))
    else:
        
        device_type ="v_dac"
        c.execute("select name from v_dac where id ='"+id+"'")
        for col in c:
            name = col[0]
            
        if (CCM == true):
            cmd = "create"
            cmd_id = get_ccm_command_id()
            action="create"
            # name="sweep"
            message = "set,element=sweep,args=9,uuid={0},action={1},element_name={2},start_current={3},stop_current={4},increment_step={5},interval_sec={6},id={7},device_type={8},device={9}"\
                    .format(cmd_id, cmd, name, start_current, stop_current, increment_step,interval_sec,id,device_type,device)

            send_ccm_msg(message)
            response = get_ccm_response(cmd_id)
            print(response)
            delete_ccm_response(cmd_id)
        else:
            c.execute("SELECT count(*) from sweep where vDAC_id = '"+id+"'")
            conn.commit()
            for col in c:
                count = col[0]
            if count == 0:
                c.execute("Insert into sweep (vDAC_id,start_current,stop_current,increment_step,increment_interval) values(?,?,?,?,?)",[id,start_current,stop_current,increment_step,interval_sec])
                conn.commit()
                print(json.JSONEncoder().encode(
                    {"status": "success", "description": "Successfully Created"}))
            else:
                c.execute("update sweep set start_current = ?, stop_current = ?,increment_step = ?,increment_interval = ? where vDAC_id = ?",[start_current,stop_current,increment_step,interval_sec,id])
                conn.commit()
                print(json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated"}))
    # name = data["name"] if "name" in data else " "
    # set_max_current = data["idac_max"] if "idac_max" in data else " "
    
    # c.execute("SELECT control_sectionName from i_dac where id='"+str(id)+"'")
    # conn.commit()
    # for col in c:
    #     control_sectionName = col[0]
    
    # query_update = c.execute('''UPDATE sweep SET name = COALESCE(?, name), set_current = COALESCE(?, set_current), set_max_current = COALESCE(?, set_max_current), edit_date = datetime() WHERE id = ? ''', [
    #                 name, start_current, set_max_current, id])
    # conn.commit()
    
    # InstantaneousCurrent = start_current
    
    # while InstantaneousCurrent <= stop_current:
    #     #print ("Instantaneous Current : ",InstantaneousCurrent)
    #     c.execute("update sweep set set_current=? where id=?",[InstantaneousCurrent,id])
    #     conn.commit()
    #     InstantaneousCurrent += increment_step
    #     time.sleep(interval_sec)
        
        
    # if InstantaneousCurrent != data["stop_current"]:
    #     c.execute("update sweep set set_current=? where id=?",[stop_current,id])
    #     conn.commit()

    # print(json.JSONEncoder().encode(
    #         {"status": "success", "description": "Successfully Updated"}))

def read_iDac_id():
    id = form.getvalue("id")
    c.execute("SELECT name,control_sectionName,state,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from i_dac where id='"+str(id)+"'")
    iDacData = []
    for col in c:
        jsonSchema = {"name": col[0],"control_sectionName":col[1], "state": col[2], "set_on_off_state": col[3], "set_current_limit": col[4],
                      "set_min_current": col[5], "set_current": col[6], "get_current": col[7], "get_hardware_id": col[8], "id": col[9]}
        iDacData.append(jsonSchema)
    
    print(json.JSONEncoder().encode(iDacData))
def read_vDac_id():
    id = form.getvalue("id")
    c.execute("SELECT name,state,set_on_off_state,set_max_current,set_min_current,set_current,get_current,get_hardware_id,id from v_dac where id='"+str(id)+"'")
    vDacData = []
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "set_on_off_state": col[2], "set_current_limit": col[3],
                      "set_min_current": col[4], "set_current": col[5], "get_current": col[6], "get_hardware_id": col[7], "id": col[8]}
        vDacData.append(jsonSchema)
    
    print(json.JSONEncoder().encode(vDacData))
def stop_sweep():
    if CCM == true:
        cmd = "stop"
        cmd_id = get_ccm_command_id()
        action="stop"
        name="sweep"
        message = "set,element=sweep,args=11,uuid={0},action={1},element_name={2},device={3}".format(cmd_id, cmd, name, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        print(json.JSONEncoder().encode({"status": "success","description" : "Sweep Stop"}))
print("Content-type:/text/json\r\n\r\n")


if(request_Type == 'get_idacs'):
    get_idacs()
if(request_Type == 'get_vdacs'):
    get_vdacs()
if(request_Type == 'Set_InstantaneousCurrent'):
    Set_InstantaneousCurrent()
if(request_Type == 'read_iDac_id'):
    read_iDac_id()
if(request_Type == 'read_vDac_id'):
    read_vDac_id()
if(request_Type == "stop_sweep"):
    stop_sweep()
c.close()
conn.close()
