import hashlib
import json
import pyodbc

#connection = pyodbc.connect(
#    'Driver={SQL Server};'
#    'Server=localhost\SQLEXPRESS;'
#    'Database=K9Data;'
#    'Trusted_Connection=yes;'
#)

with open('users_db.json', 'r') as file:
    try:
        users_db = json.load(file)
    except json.JSONDecodeError:
        users_db = {}

# Hash a password and relate the hash to a specific user input
def hash_password(password):
    password_hash = hashlib.sha256()
    password_hash.update(password.encode('utf-8'))
    storable_password = password_hash.hexdigest()
    return storable_password

# This function should update the password in the users_db
# with the new password hash
def update_password(username, old_password, new_password):
    if username not in users_db:
        return {"success": False, "message": "User does not exist."}

    old_password_hash = hash_password(old_password)
    user_authentication_result = authenticate_user(username, old_password_hash)

    if user_authentication_result['success'] == True:
        if len(new_password) < 8:
            return {"success": False, "message": "New password must be at least 8 characters long."}
        
        updated_password_hash = hash_password(new_password)
        if users_db[username]['password_hash'] == updated_password_hash:
            return {"success": False, "message": "New password cannot be the same as the old password."}
        users_db[username]['password_hash'] = updated_password_hash
        
        with open('users_db.json', 'w') as json_file:
            json.dump(users_db, json_file, indent=4)  # `indent` for pretty printing

        return {"success": True, "message": "Password updated successfully."}
    else:
        return {"success": False, "message": "Invalid password."}   
    

def reset_password(username, new_password, confirm_new_password):
    if username not in users_db:
        return {"success": False, "message": "User not found."}

    if new_password != confirm_new_password:
        return {"success": False, "message": "Passwords do not match."}

    current_user = users_db[username]
    if len(new_password) < 8:
        return {"success": False, "message": "New password must be at least 8 characters long."}
    
    new_password_hash = hash_password(new_password)
    if current_user['password_hash'] == new_password_hash:
        return {"success": False, "message": "New password cannot be the same as the old password."}
    
    current_user['password_hash'] = new_password_hash

    with open('users_db.json', 'w') as json_file:
        json.dump(users_db, json_file, indent=4)  # `indent` for pretty printing

    return {"success": True, "message": "Password successfully changed."}

def retrieve_security_question(username):
    if username in users_db.keys():
        return {"success": True, "securityQuestion": users_db[username]['security_question']}
    return {"success": False, "message": "User does not exist."}

def verify_security_answer(username, security_answer):
    security_answer_hash= hash_password(security_answer)
    if username in users_db.keys() and users_db[username]['security_answer'] == security_answer_hash:
        return {"success": True, "message": "Security answer verified."}
    return {"success": False, "message": "Security answer not verified."}

# Register a new user
def register_user(username, full_name, email, password, security_question, security_answer):
    if username in users_db.keys():
        return {"success": False, "message": "User already exists."}
    for users in users_db.keys():
        if users_db[users]['email'] == email:
            return {"success": False, "message": "Email already exists."}
        
    if len(password) < 8:
        return {"success": False, "message": "Password must be at least 8 characters long."}
    if len(username) < 4:
        return {"success": False, "message": "Username must not be at least 4 characters long."}
    
    pasword_hash = hash_password(password)
    security_answer_hash = hash_password(security_answer)

    users_db[username] = {
        'email': email,
        'full_name': full_name,
        'password_hash': pasword_hash,  # In a real application, hash the password
        'is_active': True,
        'security_question': security_question,
        'security_answer': security_answer_hash # Add appropriate security answer handling
    }

    with open('users_db.json', 'w') as json_file:
        json.dump(users_db, json_file, indent=4)  # `indent` for pretty printing

    return {"success": True, "message": "Registration successful."}

# Delete a user (for administrative purposes or account removal)
def delete_user(username):
    if username in users_db:
        del users_db[username]

        with open('users_db.json', 'w') as json_file:
            json.dump(users_db, json_file, indent=4)  # `indent` for pretty printing
        return "User deleted successfully."
    else:
        return "User not found."

# Reactivate a user account if marked inactive (for example, after temporary deactivation)
def reactivate_user(username):
    if username in users_db:
        users_db[username]['is_active'] = True

        with open('users_db.json', 'w') as json_file:
            json.dump(users_db, json_file, indent=4)  # `indent` for pretty printing
        return "User reactivated successfully."
    else:
        return "User not found."

# Deactivate a user account
def deactivate_user(username):
    if username in users_db:
        users_db[username]['is_active'] = False
        with open('users_db.json', 'w') as json_file:
            json.dump(users_db, json_file, indent=4)  # `indent` for pretty printing
        return "User deactivated successfully."
    else:
        return "User not found."
    
def authenticate_user(username, password):
    password_hash = hash_password(password)
    if username in users_db and users_db[username]['password_hash'] == password_hash:
        return {"success": True, "message": "User authenticated"}
    else:
        if username not in users_db:
            return {"success": False, "message": "User not found"}
        else:
            return {"success": False, "message": "Invalid password"}
			
	