#!/usr/bin/env python3

import logging

from .api import requires_admin

from flask import (
    Blueprint,
    flash,
    redirect,
    render_template,
    request,
)
from tentacles.globals import ctx


log = logging.getLogger(__name__)
BLUEPRINT = Blueprint("admin", __name__)


@BLUEPRINT.route("/admin", methods=["GET"])
@requires_admin
def list_files():
    if request.method == "POST":
        flash("Not supported yet", category="warning")

    return render_template("admin.html.j2")


@BLUEPRINT.route("/admin/users", methods=["POST"])
@requires_admin
def manipulate_users():
    uid = int(request.form.get("user_id", "-1"))

    match request.form.get("action"):
        case "approve":
            row = ctx.db.approve_user(uid=uid)
            ctx.db.enable_user(uid=uid)
            ctx.db.create_email(
                uid=uid,
                subject="Tentacles account approved!",
                body=render_template(
                    "approval_email.html.j2",
                    username=row.name,
                    base_url=request.root_url,
                ),
            )
            if row:
                flash(f"Approved {row.name}", category="success")

        case "enable":
            row = ctx.db.enable_user(uid=uid)
            if row:
                flash(f"Enabled {row.name}", category="success")

        case "disable":
            row = ctx.db.disable_user(uid=uid)
            if row:
                flash(f"Disabled {row.name}", category="success")

        case "passwdchng":
            ctx.db.set_user_status(uid=uid, status="passwdchng")

        case _:
            print(request.form)
            flash("Not supported yet", category="warning")
            return render_template("admin.html.j2"), 400

    return redirect("/admin")


@BLUEPRINT.route("/admin/users", methods=["GET"])
def get_users():
    return redirect("/admin")


@BLUEPRINT.route("/admin/printers", methods=["GET"])
@requires_admin
def add_printer():
    return render_template("add_printer.html.j2")


@BLUEPRINT.route("/admin/printers", methods=["POST"])
@requires_admin
def handle_add_printer():
    try:
        assert request.form["name"]
        assert request.form["url"]
        assert request.form["api_key"]
        ctx.db.try_create_printer(
            name=request.form["name"],
            url=request.form["url"],
            api_key=request.form["api_key"],
            sid=0,  # Disconnected
        )
        flash("Printer created")
        return redirect("/admin/printers")

    except Exception as e:
        log.exception("Failed to create printer")
        flash(f"Unable to create printer", category="error")

    return render_template("printers.html.j2")


@BLUEPRINT.route("/admin/printers/edit", methods=["GET"])
@requires_admin
def get_edit_printers():
    pid = int(request.args.get("id", "-1"))
    if row := ctx.db.fetch_printer(pid=pid):
        print(row)
        return render_template("edit_printer.html.j2", printer=row)
    else:
        flash("No such printer", category="error")
        return redirect("/admin"), 404


@BLUEPRINT.route("/admin/printers/edit", methods=["POST"])
@requires_admin
def handle_edit_printers():
    args = request.form.copy()
    args["id"] = int(args["id"])
    args["enabled"] = int(args["enabled"])
    args["filament_id"] = int(args["filament_id"])
    args["chassis_id"] = int(args["chassis_id"])
    args["nozzle_diameter"] = float(args["nozzle_diameter"])
    ctx.db.edit_printer(**args)
    return redirect("/admin")


@BLUEPRINT.route("/admin/files", methods=["POST"])
@requires_admin
def manipulate_files():
    fid = int(request.form.get("file_id", "-1"))

    match request.form.get("action"):
        case _:
            print(request.form)
            flash("Not supported yet", category="warning")
            return render_template("admin.html.j2"), 400

    return redirect("/admin")
