#!/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,
    send_file,
)
from tentacles.globals import ctx


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


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

    return render_template("files.html.j2")


@BLUEPRINT.route("/files", methods=["POST"])
@requires_auth
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 "download":
            file = ctx.db.fetch_file(uid=ctx.uid, fid=int(request.form.get("file_id")))
            if file:
                return send_file(
                    file.path, as_attachment=True, download_name=file.filename
                )
            else:
                flash("File not found", category="error")

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

            if os.path.exists(file.path):
                os.unlink(file.path)

            ctx.db.delete_file(uid=ctx.uid, fid=file.id)
            ctx.db.delete_file_analysis_by_fid(fid=file.id)
            ctx.db.delete_jobs_by_fid(uid=ctx.uid, fid=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")
