#!/usr/bin/env python3

import logging
import os

from .api import create_file
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("files", __name__)


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

    return render_template("files.html.j2")


@requires_auth
@BLUEPRINT.route("/files", methods=["POST"])
def manipulate_files():
    match request.form.get("action"):
        case "upload":
            resp, code = create_file()
            if 200 <= code <= 300:
                flash("File created", category="info")
            else:
                flash(resp.get("error"), category="error")
                return render_template("files.html.j2"), code

        case "delete":
            file = ctx.db.fetch_file(ctx.uid, int(request.form.get("file_id")))
            if any(job.finished_at is None for job in ctx.db.list_jobs_by_file(file.id)):
                flash("File is in use", category="error")
                return render_template("files.html.j2"), 400

            os.unlink(file.path)
            ctx.db.delete_file(ctx.uid, file.id)
            flash("File deleted", category="info")

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

    return redirect("/files")
