from fastapi import Request
from folkugat_web.model import temes as model
from folkugat_web.model.lilypond import RenderError
from folkugat_web.model.pagines import Pages
from folkugat_web.services import sessions as sessions_service
from folkugat_web.services.temes import links as links_service
from folkugat_web.services.temes import lyrics as lyrics_service
from folkugat_web.services.temes import query as temes_q
from folkugat_web.services.temes import scores as scores_service
from folkugat_web.services.temes import search as temes_s
from folkugat_web.templates import templates
from folkugat_web.utils import FnChain


def temes_pagina(request: Request, logged_in: bool, query: str):
    return templates.TemplateResponse(
        "fragments/temes/pagina.html",
        {
            "request": request,
            "logged_in": logged_in,
            "query": query,
            "Pages": Pages,
            "menu_selected_id": Pages.Temes,
        }
    )


def temes_busca(request: Request, logged_in: bool, query: str, offset: int = 0, limit: int = 10):
    temes = temes_s.busca_temes(
        query=query,
        hidden=logged_in,
        limit=limit + 1,
        offset=offset,
    )

    next_offset, prev_offset = None, None
    if len(temes) > limit:
        next_offset = offset + limit
        temes = temes[:limit]
    if offset > 0:
        prev_offset = max(offset - limit, 0)

    temes = (
        FnChain.transform(temes) |
        temes_q.temes_compute_stats |
        links_service.add_links_to_temes |
        lyrics_service.add_lyrics_to_temes |
        scores_service.add_scores_to_temes |
        list
    ).result()

    return templates.TemplateResponse(
        "fragments/temes/results.html",
        {
            "request": request,
            "logged_in": logged_in,
            "temes": temes,
            "query": query,
            "prev_offset": prev_offset,
            "next_offset": next_offset,
            "LinkType": model.LinkType,
            "ContentType": model.ContentType,
        }
    )


def tema(request: Request, logged_in: bool, tema: model.Tema):
    return templates.TemplateResponse(
        "fragments/tema/pagina.html",
        {
            "request": request,
            "logged_in": logged_in,
            "Pages": Pages,
            "LinkType": model.LinkType,
            "ContentType": model.ContentType,
            "tema": tema,
            "date_names": sessions_service.get_date_names,
        }
    )


def score_render(
    request: Request,
    score_id: int,
    score_render_url: str = "",
    errors: list[RenderError] | None = None,
):
    return templates.TemplateResponse(
        "fragments/tema/editor/score_render.html",
        {
            "request": request,
            "score_id": score_id,
            "score_render_url": score_render_url,
            "errors": errors,
        }
    )
