#!/usr/bin/env python3

import logging

from .util import is_logged_in, requires_admin

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


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


@requires_admin
@BLUEPRINT.route("/printers")
def printers():
    return render_template("printers.html.j2")


@requires_admin
@BLUEPRINT.route("/printers/add", methods=["get", "post"])
def add_printer():
    if not is_logged_in():
        return redirect("/")

    elif request.method == "POST":
        try:
            assert request.form["name"]
            assert request.form["url"]
            assert request.form["api_key"]
            ctx.db.try_create_printer(
                request.form["name"],
                request.form["url"],
                request.form["api_key"],
            )
            flash("Printer created")
            return redirect("/printers")

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

    return render_template("add_printer.html.j2")


@requires_admin
@BLUEPRINT.route("/printers/delete")
def delete_printer():
    return render_template("delete_printer.html.j2")
