#!/usr/bin/python3

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

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.Create Remote Storage")
    print("2.Update Remote Storage")
    print("3.Delete Remote Storage")
    print("4.Read Remote Storage")
    choice = int(input("select cgi Function===>"))
    if choice == 1:
        request_Type = 'create_remoteStorage'
    elif choice == 2:
        request_Type = 'update_remoteStorage'
    elif choice == 3:
        request_Type = 'delete_remoteStorage'
    elif choice == 4:
        request_Type = 'read_remoteStorage'
    else:
        print("Enter Valid choice")
    print("Reques_Type="+str(request_Type))


def form_getvalue(val):
    if val == "name":
        name = str(input("Enter name of the remote storage: "))
        return name
    if val == "state":
        state = str(input("Enter state of the remote storage: "))
        return state
    if val == "share":
        share = str(input("Enter share of the remote storage: "))
        return share
    if val == "id":
        id = str(input("Enter id of the remote storage: "))
        return id
    if val == "user":
        user = str(input("Enter User: "))
        return user
    if val == "password":
        remoteStoragePassword = str(input("Enter password: "))
        return remoteStoragePassword
    if val == "enabled":
        remoteStorageEnabled = str(input("Enter remote storage enabled: "))
        return remoteStorageEnabled


def create_remoteStorage():
    cmd = "create"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        share = form.getvalue("share")
        user = form.getvalue("user")
        password = (form.getvalue("password"))
        enabled = form.getvalue("enabled")
        name = "remote_storage"
        state = "1"
        protocol = form.getvalue("protocol")

    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        share = form_getvalue("share")
        user = form_getvalue("user")
        enabled = form_getvalue("enabled")
        password = (form_getvalue("password"))
        protocol = form.getvalue("protocol")

    query = c.execute("select count(*) from remote_storage")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount == 0:
            message = "set,element=remote_storage,args=9,uuid={0},action={1},element_name={2},state={3},share={4},user={5},password={6},enabled={7},device={8},protocol={9}"\
                .format(cmd_id, cmd, name, state, share, user, password, enabled, device,protocol)
            send_ccm_msg(message)
            response = get_ccm_response(cmd_id)
            print(response)
            delete_ccm_response(cmd_id)
        else:
            update_remoteStorage()

    else:

        if (nameCount == 0):
            query = c.execute("insert into remote_storage(share,user,password,enabled,cr_date,protocol ) values(?,?,?,?,datetime(),?)", [
                              share, user, password, enabled,protocol])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Created"})))
        else:
            update_remoteStorage()

    # c.close()
    # conn.close()


def update_remoteStorage():
    cmd = "update"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        share = form.getvalue("share")
        user = form.getvalue("user")
        password =(form.getvalue("password"))
        enabled = form.getvalue("enabled")
        name = "remote_storage"
        state = "1"
        protocol = form.getvalue("protocol") 
    else:
        name = form_getvalue("name")
        state = form_getvalue("state")
        share = form_getvalue("share")
        id = form_getvalue("id")
        user = form_getvalue("user")
        password = (form_getvalue("password"))
        enabled = form_getvalue("enabled")
        protocol = form.getvalue("protocol") 

    query = c.execute("select count(*) from remote_storage")
    nameCount = c.fetchone()[0]

    if (CCM == true):
        if nameCount > 0:
            message = "set,element=remote_storage,args=9,uuid={0},action={1},element_name={2},state={3},share={4},user={5},password={6},enabled={7},device={8},protocol={9}"\
                .format(cmd_id, cmd, name, state, share, user, password, enabled, device,protocol)
            send_ccm_msg(message)
            response = get_ccm_response(cmd_id)
            print(response)
            delete_ccm_response(cmd_id)
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Name Already exists"})))

    else:

        if (nameCount > 0):
            query = c.execute("update remote_storage set share=?,user=?,password=?,enabled=?,edit_date=datetime(),protocol=?", [
                        share, user, password, enabled,protocol])
            conn.commit()
            print((json.JSONEncoder().encode(
                {"status": "success", "description": "Successfully Updated"})))
        else:
            print((json.JSONEncoder().encode(
                {"status": "fail", "description": "Name Already exists"})))

    c.close()
    conn.close()


def delete_remoteStorage():
    cmd = "delete"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
        name = form.getvalue("name")
        name = "remote_storage"
    else:
        id = form_getvalue("id")
        name = form_getvalue("name")

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

    c.close()
    conn.close()



def read_remoteStorage():
    cmd = "read"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        id = form.getvalue("id")
    else:
        id = form_getvalue("id")
    query = c.execute(
        "select name,state,share,user,password,id,enabled,protocol from remote_storage")
    dbData = []
    for col in c:
        jsonSchema = {"name": col[0], "state": col[1], "share": col[2], "user": col[3],"password": (col[4]), "id": col[5], "enabled": col[6],"protocol":col[7]}
        dbData.append(jsonSchema)
    print(json.JSONEncoder().encode(dbData))

def password_hidden():
    password_type = form.getvalue("hidden")
    query = c.execute("update remote_storage set pwd_hide=?", [password_type])
    conn.commit()
    print((json.JSONEncoder().encode({"status": "success", "description": "Password Type Set Successfull Updated"})))

def read_password_hidden():
    query = c.execute(
        "select pwd_hide from remote_storage")
    dbData = []
    for col in c:
        jsonSchema = {"type": col[0]}
        dbData.append(jsonSchema)
    print(json.JSONEncoder().encode(dbData))
    
print("Content-type:text/html\r\n\r\n")



if(request_Type == 'create_remoteStorage'):
    create_remoteStorage()
elif(request_Type == 'update_remoteStorage'):
    update_remoteStorage()
elif(request_Type == 'delete_remoteStorage'):
    delete_remoteStorage()
elif(request_Type == 'password_hidden'):
    password_hidden()
elif(request_Type == 'read_passwordHidden'):
    read_password_hidden()
else:
    read_remoteStorage()
