from fastapi import HTTPException, Request
from folkugat_web.api.router import get_router
from folkugat_web.fragments import set_page
from folkugat_web.model import playlists
from folkugat_web.services import auth
from folkugat_web.services import playlists as playlists_service
from folkugat_web.templates import templates

router = get_router()


def set_description(set_: playlists.Set) -> str:
    tema_names = [tis.tema.title if tis.tema else "Desconegut" for tis in set_.temes]
    return " i ".join(filter(bool, [
        ", ".join(tema_names[:-1]),
        tema_names[-1]
    ]))


@router.get("/llista/{playlist_id}/set/{set_id}")
def page(
    request: Request,
    logged_in: auth.LoggedIn,
    playlist_id: int,
    set_id: int,
):
    set_ = playlists_service.get_set(playlist_id=playlist_id, set_id=set_id)
    if not set_:
        raise HTTPException(status_code=404, detail="Set not found")
    set_ = playlists_service.add_temes_to_set(set_)
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request,
            "page_title": "Folkugat - Set",
            "page_description": set_description(set_=set_),
            "content": f"/api/content/llista/{playlist_id}/set/{set_id}",
            "logged_in": logged_in,
        }
    )


@router.get("/api/content/llista/{playlist_id}/set/{set_id}")
async def contingut(
    request: Request,
    logged_in: auth.LoggedIn,
    playlist_id: int,
    set_id: int,
):
    return await set_page.pagina(
        request=request,
        playlist_id=playlist_id,
        set_id=set_id,
        logged_in=logged_in,
    )
