from fastapi import Request
from folkugat_web.model import temes as model
from folkugat_web.model.pagines import Pages
from folkugat_web.services.temes import query as temes_q
from folkugat_web.services.temes import search as temes_s
from folkugat_web.templates import templates


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


def temes_busca_result(request: Request, tema: model.Tema, logged_in: bool):
    return templates.TemplateResponse(
        "fragments/temes/result.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
            "LinkSubtype": model.LinkSubtype,
            "LinkType": model.LinkType,
        }
    ).body.decode('utf-8')


def temes_busca(request: Request, query: str, logged_in: bool):
    temes = temes_s.busca_temes(query)
    return '\n'.join(
        [temes_busca_result(request, tema, logged_in)
         for tema in temes]
    )


def tema(request: Request, tema_id: int, logged_in: bool):
    tema = temes_q.get_tema_by_id(tema_id)
    return templates.TemplateResponse(
        "fragments/tema/pagina.html",
        {
            "request": request,
            "logged_in": logged_in,
            "Pages": Pages,
            "LinkSubtype": model.LinkSubtype,
            "LinkType": model.LinkType,
            "tema": tema,
        }
    )
