import os
from flask import Flask, request, render_template, redirect, session

app = Flask(__name__, static_folder="public")
app.secret_key = "very-secret-key-for-lab3"

PROFILE_IMAGE_DIR = os.path.join(app.static_folder, "images", "profile")
PROFILE_IMAGE_PATH = os.path.join(PROFILE_IMAGE_DIR, "profile.jpg")

ALLOWED_USERS = {
    "test": "test123",
    "admin": "n0h4x0rz-plz",
}

DATABASE_FILE = "database.txt"


@app.route("/")
def index():
    # TODO Task 01: render the index page using child template
    return render_template("index.html")

@app.route("/second")
def second():
    # TODO Task 01: render the second page using child template
    return render_template("second.html")

# TODO Task 02: Authentication
@app.route("/login", methods=["GET", "POST"])
def login():
    error_msg = ""
    if request.method == "POST":
        username = request.form.get("username", "")
        password = request.form.get("password", "")
        
        if username in ALLOWED_USERS and ALLOWED_USERS[username] == password:
            session["authenticated"] = True
            session["username"] = username
            return redirect("/")
        else:
            error_msg = "Invalid username or password!"
            
    return render_template("login.html", error_msg=error_msg)

@app.route("/logout")
def logout():
    # TODO Task 02: clear authentication status
    session.clear()
    return redirect("/")

@app.context_processor
def inject_template_vars():
    return {
        "todo_var": "TODO_inject_common_template_variables"
    }


def read_database(filename):
    try:
        with open(filename, "rt") as f:
            line1 = f.readline().strip()
            line2 = f.readline().strip()
            line3 = f.readline().strip()
            age = int(line3) if line3 else 0
            return {
                "first_name": line1,
                "last_name": line2,
                "age": age,
            }
    except FileNotFoundError:
        return {
            "first_name": "",
            "last_name": "",
            "age": "",
        }

def write_database(filename, data):
    with open(filename, "wt") as f:
        f.write(f"{data.get('first_name', '')}\n")
        f.write(f"{data.get('last_name', '')}\n")
        f.write(f"{data.get('age', '')}\n")

# TODO Task 04: Save Account Details
@app.route("/account-details", methods=["GET", "POST"])
def save_account():
    if request.method == "POST":
        first_name = request.form.get("first_name", "")
        last_name = request.form.get("last_name", "")
        age = request.form.get("age", "")
        
        data = {
            "first_name": first_name,
            "last_name": last_name,
            "age": age
        }
        write_database(DATABASE_FILE, data)

        if "profile_pic" in request.files:
            file = request.files["profile_pic"]
            if file and file.filename != "":
                file.save(PROFILE_IMAGE_PATH)
        
        return redirect("/account-details")

    data = read_database(DATABASE_FILE)
    return render_template("account-details.html", **data)

@app.errorhandler(404)
def error404(code):
    return "HTTP Error 404 - Page Not Found"


if __name__ == "__main__":
    app.run(debug=True, port=5000)

