import gradio as gr
import os
import hashlib
import json

# Simulated user database
USER_DATABASE = "users.json"
DOCUMENTS_DIR = "documents"

# Helper function to load user data
def load_users():
    if os.path.exists(USER_DATABASE):
        with open(USER_DATABASE, "r") as file:
            return json.load(file)
    return {}

# Helper function to save user data
def save_users(users):
    with open(USER_DATABASE, "w") as file:
        json.dump(users, file)

# Create a user database if it doesn't exist
if not os.path.exists(USER_DATABASE):
    save_users({})

# Create a documents directory if it doesn't exist
if not os.path.exists(DOCUMENTS_DIR):
    os.makedirs(DOCUMENTS_DIR)

# User authentication
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

def authenticate_user(username, password):
    users = load_users()
    if username in users and users[username] == hash_password(password):
        return True
    return False

def register_user(username, password):
    users = load_users()
    if username in users:
        return False
    users[username] = hash_password(password)
    save_users(users)
    return True

# Gradio app functions
def login(username, password):
    if authenticate_user(username, password):
        return f"Welcome {username}", username
    return "Invalid credentials", None

def register(username, password):
    if register_user(username, password):
        return "User registered successfully. Please login."
    return "Username already exists"

def upload_file(username, file):
    if username:
        user_dir = os.path.join(DOCUMENTS_DIR, username)
        if not os.path.exists(user_dir):
            os.makedirs(user_dir)
        if isinstance(file, gr.inputs.InputComponent):
            # If it's an InputComponent object, it's a file upload
            file_path = os.path.join(user_dir, file.name)
            with open(file_path, "wb") as f:
                f.write(file.getvalue())
            return f"File {file.name} uploaded successfully."
        else:
            # If it's a file-like object, write its content as usual
            file_path = os.path.join(user_dir, file.name)
            with open(file_path, "wb") as f:
                f.write(file.read())
            return f"File {file.name} uploaded successfully."
    return "You must be logged in to upload files."



def view_files(username):
    if username:
        user_dir = os.path.join(DOCUMENTS_DIR, username)
        if not os.path.exists(user_dir):
            return []
        return os.listdir(user_dir)
    return []

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("# Document Management System")

    login_session = gr.State(None)

    with gr.Tab("Login"):
        username = gr.Textbox(label="Username")
        password = gr.Textbox(label="Password", type="password")
        login_button = gr.Button("Login")
        login_output = gr.Textbox(label="Login Status")

        def handle_login(username, password):
            message, session = login(username, password)
            login_session.value=session
            return message, session

        login_button.click(handle_login, [username, password], [login_output, login_session])

    with gr.Tab("Register"):
        reg_username = gr.Textbox(label="Username")
        reg_password = gr.Textbox(label="Password", type="password")
        register_button = gr.Button("Register")
        register_output = gr.Textbox(label="Registration Status")

        register_button.click(register, [reg_username, reg_password], register_output)

    with gr.Tab("Upload Document"):
        file_upload = gr.File(label="Upload your document")
        upload_button = gr.Button("Upload")
        upload_output = gr.Textbox(label="Upload Status")

        def handle_upload(file):
            username = login_session.value
            return upload_file(username, file)

        upload_button.click(handle_upload, file_upload, upload_output)

    with gr.Tab("View Documents"):
        view_button = gr.Button("View Documents")
        document_list = gr.Textbox(label="Your Documents")

        def handle_view_files():
            username = login_session.get()
            files = view_files(username)
            return "\n".join(files)

        view_button.click(handle_view_files, None, document_list)

demo.launch()
error i got : if isinstance(file, gr.inputs.InputComponent):
AttributeError: module 'gradio' has no attribute 'inputs'