#!/usr/bin/python3


import cgitb
import cgi
import json
import sqlite3
from db import *
from globalSettings import *
from global_func import *

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


cgitb.enable()

device = DeviceName

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

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


def start_calibration():
    print((json.JSONEncoder().encode(
        {"status": "success", "description": "success "})))


if(request_Type == 'start_calibration'):
    start_calibration()

if(request_Type == "read_calibration"):
    c.execute("select * from calibration")
    dbData = []
    for col in c:
        jsonSchema = {"id": col[0],"ring_start_voltage_1" : col[1],"ring_stop_voltage_1" : col[2],"ring_increment_1": col[3],"r1_cur": col[4],"ring_start_voltage_2": col[5],"ring_stop_voltage_2": col[6],"ring_increment_2": col[7],"r2_cur": col[8],"phase_start_voltage": col[9],"phase_stop_voltage": col[10],"phase_increment": col[11],"phase_cur": col[12],"gain_start_current": col[13],"gain_stop_current": col[14],"gain_inc": col[15],"gain_cur": col[16],"start_temperature":col[17],"stop_temperature" : col[18],"temp_inc" : col[19],"temp_cur" : col[20],"soa_start" : col[21],"soa_stop" : col[22],"soa_inc" : col[23],"soa_current" : col[24],"detector" : col[25],"file_location" : col[26],"cr_date" : col[27],"edit_date" : col[28],"del_date" : col[29]}
        dbData.append(jsonSchema)
    print((json.JSONEncoder().encode(dbData)))

if(request_Type == "create_calibration"):
    ring_start_voltage_1 = form.getvalue('ring_start_voltage_1')
    ring_stop_voltage_1 = form.getvalue('ring_stop_voltage_1')
    ring_increment_1 = form.getvalue('ring_increment_1')
    r1_current = form.getvalue('r1_current')
    ring_start_voltage_2 = form.getvalue('ring_start_voltage_2')
    ring_stop_voltage_2 = form.getvalue('ring_stop_voltage_2')
    ring_increment_2 = form.getvalue('ring_increment_2')
    r2_current = form.getvalue('r2_current')
    phase_start_voltage = form.getvalue('phase_start_voltage')
    phase_stop_voltage = form.getvalue('phase_stop_voltage')
    phase_increment = form.getvalue('phase_increment')
    phase_current = form.getvalue('phase_current')
    gain_start_current = form.getvalue('gain_start_current')
    gain_stop_current = form.getvalue('gain_stop_current')
    gain_increment = form.getvalue('gain_increment')
    gain_current = form.getvalue('gain_current')
    start_temperature = form.getvalue('start_temperature')
    stop_temperature = form.getvalue('stop_temperature')
    temp_increment = form.getvalue('temp_increment')
    temp_current = form.getvalue('temp_current')
    detector = form.getvalue('detector')
    location = form.getvalue('location')
    soa_start = form.getvalue('soa_start')
    soa_stop = form.getvalue('soa_stop')
    soa_inc = form.getvalue('soa_inc')
    soa_current = form.getvalue('soa_current')
    
    if CCM==true:
        c.execute("select count(*) from calibration")
        if(c.fetchone()[0] == 0):
            cmd = "create"
        else:
            cmd = "update"
        cmd_id = get_ccm_command_id()
        action="create"
        name="calibration"
        message = """set,element=calibration,args=11,uuid={0},action={1},start_volt1={2},stop_volt1={3},ring_inc_1={4},start_volt2={5},stop_volt2={6},ring_inc_2={7},phase_start={8},phase_stop={9},phase_inc={10},gain_start={11},gain_stop={12},start_temp={13},stop_temp={14},detector={15},location={16},gain_increment={17},temp_increment={18}, soa_start={19},soa_stop={20},soa_inc={21}, device={22}"""\
                    .format(cmd_id,cmd,ring_start_voltage_1,ring_stop_voltage_1,ring_increment_1,ring_start_voltage_2,ring_stop_voltage_2,ring_increment_2,phase_start_voltage,phase_stop_voltage,phase_increment,gain_start_current,gain_stop_current,start_temperature,stop_temperature,detector,location,gain_increment,temp_increment,soa_start,soa_stop,soa_inc,device)

        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
        
    else:
        c.execute("select count(*) from calibration")
        if(c.fetchone()[0] == 0):
            c.execute("insert into calibration (ring_start_voltage_1,ring_stop_voltage_1,ring_increment_1,ring_start_voltage_2,ring_stop_voltage_2,ring_increment_2,phase_start_voltage,phase_stop_voltage,phase_increment,gain_start_current,gain_stop_current,start_temperature,stop_temperature,detector,file_location ,soa_current,r1_cur,r2_cur,phase_cur,gain_inc,gain_cur,temp_inc,temp_cur,soa_start,soa_stop,soa_inc) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[ring_start_voltage_1,ring_stop_voltage_1,ring_increment_1,ring_start_voltage_2,ring_stop_voltage_2,ring_increment_2,phase_start_voltage,phase_stop_voltage,phase_increment,gain_start_current,gain_stop_current,start_temperature,stop_temperature,detector,location ,soa_current,r1_current,r2_current,phase_current,gain_increment,gain_current,temp_increment,temp_current,soa_start,soa_stop,soa_inc])
            
            print((json.JSONEncoder().encode({"status": "success", "description": "Created SuccessFully"})))
        else:
            c.execute("update calibration set ring_start_voltage_1= ? ,ring_stop_voltage_1= ? ,ring_increment_1= ? ,ring_start_voltage_2= ? ,ring_stop_voltage_2= ? ,ring_increment_2= ? ,phase_start_voltage= ? ,phase_stop_voltage= ? ,phase_increment= ? ,gain_start_current= ? ,gain_stop_current= ? ,start_temperature= ? ,stop_temperature= ? ,detector= ? ,file_location = ? ,soa_current = ?,r1_cur =?,r2_cur=?,phase_cur=?,gain_inc=?,gain_cur=?,temp_inc=?,temp_cur=?,soa_start=?,soa_stop=?,soa_inc=?",[ring_start_voltage_1,ring_stop_voltage_1,ring_increment_1,ring_start_voltage_2,ring_stop_voltage_2,ring_increment_2,phase_start_voltage,phase_stop_voltage,phase_increment,gain_start_current,gain_stop_current,start_temperature,stop_temperature,detector,location ,soa_current,r1_current,r2_current,phase_current,gain_increment,gain_current,temp_increment,temp_current,soa_start,soa_stop,soa_inc])
            print((json.JSONEncoder().encode({"status": "success", "description": "Updated Successfully"})))

    conn.commit()
    c.close()
    conn.close()

if request_Type == 'stop_calibration':
    cmd = "stop"
    cmd_id = get_ccm_command_id()
    action="stop"
    name="stop_calibration"
    message = """set,element=stop_calibration,args=11,uuid={0},action={1},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)