from fastapi import HTTPException, Request
from folkugat_web.model.pagines import Pages
from folkugat_web.model.temes import ContentType, LinkType
from folkugat_web.services import playlists as playlists_service
from folkugat_web.services import sessions as sessions_service
from folkugat_web.templates import templates


async def pagina(request: Request, playlist_id: int, set_id: int, logged_in: bool):
    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_)
    set_ = await playlists_service.add_set_score_to_set(set_)
    return templates.TemplateResponse(
        "fragments/llista/set/pagina.html",
        {
            "request": request,
            "logged_in": logged_in,
            "Pages": Pages,
            "set": set_,
            "session": None,
            "date_names": sessions_service.get_date_names,
            "LinkType": LinkType,
            "ContentType": ContentType,
        }
    )


async def live(request: Request, logged_in: bool):
    session = sessions_service.get_live_session()
    set_ = None
    if session and session.id:
        playlist = sessions_service.get_session_setlist(session_id=session.id)
        if playlist and playlist.sets:
            set_ = playlists_service.add_temes_to_set(playlist.sets[-1])
            set_ = await playlists_service.add_set_score_to_set(set_)
    return templates.TemplateResponse(
        "fragments/llista/set/pagina.html",
        {
            "request": request,
            "logged_in": logged_in,
            "Pages": Pages,
            "session": session,
            "set": set_,
            "date_names": sessions_service.get_date_names,
            "LinkType": LinkType,
            "ContentType": ContentType,
        }
    )


async def live_set(request: Request, logged_in: bool):
    session = sessions_service.get_live_session()
    set_ = None
    if session and session.id:
        playlist = sessions_service.get_session_setlist(session_id=session.id)
        if playlist and playlist.sets:
            set_ = playlists_service.add_temes_to_set(playlist.sets[-1])
            set_ = await playlists_service.add_set_score_to_set(set_)
    return templates.TemplateResponse(
        "fragments/llista/set/set_page.html",
        {
            "request": request,
            "logged_in": logged_in,
            "Pages": Pages,
            "session": session,
            "set": set_,
            "date_names": sessions_service.get_date_names,
            "LinkType": LinkType,
            "ContentType": ContentType,
        }
    )
