from dataclasses import dataclass
from typing import Dict, List

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

from src.config import Configuration
from src.internals.internal_types import PageProps
from src.lib.artist import get_artist
from src.lib.dms import get_all_dms, get_all_dms_by_query, get_all_dms_by_query_count, get_all_dms_count
from src.types.kemono import Approved_DM
from src.utils.utils import get_query_parameters_dict, parse_int, positive_or_none, step_int


@dataclass
class DMsProps(PageProps):
    currentPage = "artists"
    count: int
    limit: int
    dms: List[Approved_DM]


dms_bp = Blueprint("dms", __name__)


@dms_bp.route("/dms")
def get_dms():
    base = get_query_parameters_dict(request, on_errors="ignore", clean_query_string=True)

    limit = 50
    max_offset = limit * 1000  # only load 1000 pages of any result
    offset = positive_or_none(step_int(parse_int(base.pop("o", 0), 0), limit))
    if offset is None or offset > max_offset:
        return redirect(url_for("dms.get_dms"))
    query = base.get("q", "").strip()[: Configuration().webserver["max_full_text_search_input_len"]]

    if not query or len(query) < 3:
        total_count = get_all_dms_count()
        if offset > total_count:
            return redirect(url_for("dms.get_dms"))
        dms = get_all_dms(offset, limit)
    else:
        total_count = get_all_dms_by_query_count(query)
        if offset > total_count:
            return redirect(url_for("dms.get_dms"))
        dms = get_all_dms_by_query(query, offset, limit)

    props = DMsProps(count=total_count, limit=limit, dms=dms)

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