#!/usr/bin/python3

import csv
import cgi
from all_paths import *
from globalSettings import *
from global_func import *
import sqlite3
import json
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 loadCSVtoDB_regs():
    with open(RegRefsFilePath, 'r') as file:
        csv_reader = csv.reader(file)
        header = next(csv_reader)
        for row in csv_reader:
            try:
                placeholders = ', '.join(['?' for _ in row])
                query = f'INSERT INTO reg_synth (reg_name,address,value) VALUES ({placeholders})'
                c.execute(query, row)
                conn.commit()
            except Exception as e:
                pass
def readAllReg():
    c.execute("SELECT * FROM reg_synth limit 10000")
    rows = c.fetchall()
    headers = ["RegName", "Address", "Value"]
    dbData = []
    for row in rows:
        jsonSchema = {"id": row[0],"reg_name": row[1],"address": row[2],"value": row[3]}
        dbData.append(jsonSchema)
    print(json.JSONEncoder().encode({"data": dbData, "headers": headers}))

def readRFReg():
    if(GUI == true):
        reg_name = form.getvalue("reg_name")
        value = form.getvalue("value")
    else:
        reg_name = input("Enter register name =>")
        value =input("Enter value =>")
    
    c.execute("SELECT * FROM reg_synth where reg_name =? and value = ? ",[reg_name,value])
    row = c.fetchone()
    if(row):
        print(json.JSONEncoder().encode({"id": row[0],"reg_name": row[1],"address": row[2],"value": row[3]}))
    else:
        print(json.JSONEncoder().encode({}))

def readRFRegById():
    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = input("Enter RF Reg id =>")
    
    c.execute("SELECT * FROM reg_synth where id =? ",[id])
    row = c.fetchone()
    if(row):
        print(json.JSONEncoder().encode({"id": row[0],"reg_name": row[1],"address": row[2],"value": row[3]}))
    else:
        print(json.JSONEncoder().encode({}))
    
def writeRFReg():
    cmd = "create_reg"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        reg_name = form.getvalue("reg_name")
        address = form.getvalue("address")
        value = form.getvalue("value")
    else:
        reg_name = input("Enter Register name")
        address = input("Enter Address")
        value =input("Enter Value =>")
    message = "set,element=RFReg,args=11,uuid={0},action={1},reg_name={2},address={3},value={4},device={5}".format(cmd_id, cmd, reg_name, address, value,device)
    send_ccm_msg(message)
    res = get_ccm_response(cmd_id)
    response = json.loads(res)
    delete_ccm_response(cmd_id)
    print(json.JSONEncoder().encode(response))

def updateRfReg():
    cmd = "update_reg"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        reg_name = form.getvalue("reg_name")
        address = form.getvalue("address")
        value = form.getvalue("value")
        id = form.getvalue("id")
    else:
        reg_name = input("Enter Register name")
        address = input("Enter Address")
        value =input("Enter Value =>")
        id =input("Enter RF Reg Id =>")
    message = "set,element=RFReg,args=11,uuid={0},action={1},reg_name={2},address={3},value={4},id={5},device={6}".format(cmd_id, cmd, reg_name, address, value,id,device)
    send_ccm_msg(message)
    res = get_ccm_response(cmd_id)
    response = json.loads(res)
    delete_ccm_response(cmd_id)
    print(json.JSONEncoder().encode(response))

def deleteRFReg():
    cmd = "delete_reg"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = input("Enter RF Reg id =>")
    message = "set,element=RFReg,args=11,uuid={0},action={1},id={2},device={3}".format(cmd_id, cmd,id,device)
    send_ccm_msg(message)
    res = get_ccm_response(cmd_id)
    response = json.loads(res)
    delete_ccm_response(cmd_id)
    print(json.JSONEncoder().encode(response))


print("Content-type:/text/html\r\n\r\n")
if(request_Type == "loadCSVtoDB_reg"):
    loadCSVtoDB_regs()
elif(request_Type == "readAllReg"):
    readAllReg()
elif(request_Type == "readRF_reg"):
    readRFReg()
elif(request_Type == "readRFRegById"):
    readRFRegById()
elif(request_Type == "saveRfReg"):
    writeRFReg()
elif(request_Type == "updateRfReg"):
    updateRfReg()
elif(request_Type == "deleteRfReg"):
    deleteRFReg()
# loadCSVtoDB_regs()
c.close()
conn.close()