#!/usr/bin/python3

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


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

device = DeviceName

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

else:
    print("1.Update Enable SSH")
    print("1.Read Enable SSH")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'udpate_enable_ssh'
    if choice == 1:
        request_Type = 'read_enable_ssh'
    else:
        print("Enter Valid choice")


def udpate_enable_ssh():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    enable_ssh = form.getvalue('type')
    enabled = form.getvalue('enabled')
    if (CCM == true):
        message = "set,element=enable_ssh,args=14,uuid={0},action={1},enable_ssh={2},enabled={3},device={4}"\
            .format(cmd_id, cmd, enable_ssh,enabled, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        c.execute("update enable_ssh SET enable_ssh =?, enabled =? ", (enable_ssh, enabled))
        conn.commit()
        print(json.JSONEncoder().encode({"description": "Enable SSH updated Successfully"}))

def udpate_reverse_ssh():
    cmd = "update_reverse"
    cmd_id = get_ccm_command_id()
    enable_reverse = form.getvalue('enable_reverse')
    rev_enabled = form.getvalue('rev_enabled')
    if (CCM == true):
        message = "set,element=enable_ssh,args=14,uuid={0},action={1},enable_reverse={2},rev_enabled={3},device={4}"\
            .format(cmd_id, cmd, enable_reverse,rev_enabled, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        print(response)
        delete_ccm_response(cmd_id)
    else:
        c.execute("update enable_ssh SET enable_reverse =?, rev_enabled =? ", (enable_reverse, rev_enabled))
        conn.commit()
        print(json.JSONEncoder().encode({"description": "Enable SSH updated Successfully"}))

def read_enable_ssh():
    c.execute("SELECT enable_ssh, enabled FROM enable_ssh")
    data = c.fetchone()
    print(json.JSONEncoder().encode({"enable_ssh" : data[0], "enabled" : data[1]}))

def read_reverse_ssh():
    c.execute("SELECT enable_reverse, rev_enabled FROM enable_ssh")
    data = c.fetchone()
    print(json.JSONEncoder().encode({"enable_reverse" : data[0], "rev_enabled" : data[1]}))
    

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

if(request_Type == 'udpate_enable_ssh'):
    udpate_enable_ssh()
elif(request_Type == 'udpate_reverse_ssh'):
    udpate_reverse_ssh()
elif(request_Type == 'read_reverse_ssh'):
    read_reverse_ssh()
else:
    read_enable_ssh()