#!/usr/bin/python3
import cgitb
import cgi
import json
import sqlite3
from db import *
from globalSettings import *
from global_func import *
from clearTextPwd import *


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 createUser():
    username = form.getvalue('username')
    firstname = form.getvalue('firstName')
    lastname = form.getvalue('lastName')
    email = form.getvalue('email')
    password = form.getvalue('password')
    phone = form.getvalue('phone')
    query = c.execute("select count(*) from person where username = ?",[username])
    count = c.fetchone()[0]
    if count == 0:
        query = c.execute("insert into person(userName,FirstName,LastName,contactEmail,password,contactPhone ) values(?,?,?,?,?,?)",[username,firstname,lastname,email,password,phone])

        conn.commit()
        print((json.JSONEncoder().encode({"status": "success", "description": "User Created Successfully!"})))
    else:
        print((json.JSONEncoder().encode({"status": "fail", "description": "User Already Exists!"})))
    c.close()
    conn.close()
def getUserList():
    query = c.execute("select id,username from person")
    dbData = []
    for col in c:
        jsonSchema = {"id":col[0],"username": col[1]}
        dbData.append(jsonSchema)
    print(json.JSONEncoder().encode(dbData))
print("Content-type:text/html\r\n\r\n")

def getUserDetails():
    id = form.getvalue("id")
    query = c.execute("select id,userName,FirstName,LastName,contactEmail,password,contactPhone,password_hidden from person where id = ?",[id])
    dbData = []
    for col in c:
        jsonSchema = {"id":col[0],"username": col[1],"firstname": col[2],"lastname": col[3],"email": col[4],"password": pwd_decoding(col[5]),"phone": col[6],"password_hidden": col[7]}
        dbData.append(jsonSchema)
    print(json.JSONEncoder().encode(dbData))
def updateUser():
    id = form.getvalue('id')
    firstname = form.getvalue('firstName')
    lastname = form.getvalue('lastName')
    password = form.getvalue('password')
    phone = form.getvalue('phone')
    query = c.execute("update person set FirstName =?, LastName = ?,password = ?, contactPhone = ? where id = ?",[firstname,lastname,pwd_encoding(password),phone,id])
    conn.commit()
    print(json.JSONEncoder().encode({"status": "success","description" : "User Updated Successfully!"}))

def deleteUser():
    id = form.getvalue('id')
    query = c.execute("delete from person where id = ?",[id])
    conn.commit()
    print(json.JSONEncoder().encode({"status": "success","description" : "User Deleted Successfully!"}))

def password_hidden():
    id = form.getvalue('id')
    password_hidden = form.getvalue('hidden')
    query = c.execute("update person set password_hidden =? where id = ?",[password_hidden,id])
    conn.commit()
    print(json.JSONEncoder().encode({"status": "success","description" : "Hidden Password updated Successfully!"}))

if(request_Type == 'createUser'):
    createUser()
elif(request_Type == 'getUserList'):
    getUserList()
elif(request_Type == 'getUserDetails'):
    getUserDetails()
elif(request_Type == 'updateUser'):
    updateUser()
elif(request_Type == 'deleteUser'):
    deleteUser()
elif(request_Type == 'password_hidden'):
    password_hidden()