from flask import Blueprint, flash, make_response, redirect, render_template, request, url_for, g

from src.config import Configuration
from src.lib.filehaus import get_all_shares_count, get_files_for_share, get_share, get_shares
from src.utils.utils import parse_int, positive_or_none, step_int

filehaus_bp = Blueprint("filehaus", __name__)


@filehaus_bp.route("/share/<share_id>")
def get_share_handler(share_id: str):
    base = request.args.to_dict()
    base.pop("o", None)

    props = dict(currentPage="shares")
    share = get_share(int(share_id)) if share_id.isdigit() else None
    if share is None:
        response = redirect(url_for("filehaus.get_shares_page"))
        return response

    share_files = get_files_for_share(share["id"])

    response = make_response(
        render_template("share.html", share_files=share_files, share=share, props=props, base=base),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=60"
    return response


@filehaus_bp.route("/shares")
def get_shares_page():
    base = request.args.to_dict()
    base.pop("o", None)

    limit = 50
    offset = positive_or_none(step_int(parse_int(request.args.get("o"), 0), limit))
    # query = request.args.get('q')

    shares = None
    total_count = None
    (shares, total_count) = get_share_page(offset, limit)

    props = dict(currentPage="shares", count=total_count, shares=shares, limit=limit)

    response = make_response(
        render_template(
            "shares.html",
            props=props,
            base=base,
        ),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=60"
    return response


def get_share_page(offset: int, limit: int):
    posts = get_shares(offset, limit)
    total_count = get_all_shares_count()
    return posts, total_count


@filehaus_bp.route("/posts/upload")
def upload_post():
    account = g.get("account")
    if Configuration().filehaus["requires_account"] and account is None:
        flash("Filehaus uploading requires an account.")
        return redirect(url_for("account.get_login"))
    required_roles = Configuration().filehaus["required_roles"]
    if len(required_roles) and account.role not in required_roles:
        flash(
            "Filehaus uploading requires elevated permissions. " "Please contact the administrator to change your role."
        )
        return redirect(url_for("account.get_account"))
    props = {"currentPage": "posts"}
    response = make_response(render_template("upload.html", props=props), 200)
    response.headers["Cache-Control"] = "s-maxage=60"
    return response
