#!/usr/bin/env python3

import logging

from .util import requires_auth

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


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


@BLUEPRINT.route("/jobs", methods=["GET"])
@requires_auth
def list_jobs():
    return render_template("jobs.html.j2")


@BLUEPRINT.route("/jobs", methods=["POST"])
@requires_auth
def manipulate_jobs():
    match request.form.get("action"):
        case "enqueue":
            ctx.db.create_job(uid=ctx.uid, fid=int(request.form.get("file_id")))
            flash("Job created!", category="info")

        case "duplicate":
            if job := ctx.db.fetch_job(
                uid=ctx.uid, jid=int(request.form.get("job_id"))
            ):
                ctx.db.create_job(uid=ctx.uid, fid=job.file_id)
                flash("Job created!", category="info")
            else:
                flash("Could not duplicate", category="error")

        case "cancel":
            ctx.db.cancel_job(
                uid=None if ctx.is_admin else ctx.uid,
                jid=int(request.form.get("job_id")),
            )
            flash("Cancellation reqested", category="info")

        case "delete":
            ctx.db.delete_job(
                uid=None if ctx.is_admin else ctx.uid,
                jid=int(request.form.get("job_id")),
            )
            flash("Job deleted", category="info")

        case _:
            print(request.form)
            flash("Unsupported operation", category="error")
            return render_template("jobs.html.j2"), 400

    return redirect("/jobs")
