from fastapi import Request
from fastapi.responses import HTMLResponse
from folkugat_web.model import sessions as model
from folkugat_web.services import playlists as playlists_service
from folkugat_web.services import sessions as service
from folkugat_web.templates import templates


def sessio_en_directe(request: Request):
    session = service.get_live_session()
    if not session:
        return HTMLResponse()
    if not session.id:
        raise RuntimeError("Got a session without id!")

    current_set = None
    if playlist := service.get_session_setlist(session_id=session.id):
        if playlist.sets:
            current_set = playlists_service.add_temes_to_set(playlist.sets[-1])

    return templates.TemplateResponse(
        "fragments/marquee.html",
        {
            "request": request,
            "session": session,
            "current_set": current_set,
        }
    )


def start_live_session(request: Request, session_id: int):
    service.set_live_session(session_id=session_id)
    session = model.Session(id=session_id)
    return templates.TemplateResponse(
        "fragments/sessio/live/stop.html",
        {
            "request": request,
            "session": session,
        },
        headers={
            "HX-Trigger": "reload-marquee"
        }
    )


def stop_live_session(request: Request, session_id: int):
    service.stop_live_sessions()
    session = model.Session(id=session_id)
    return templates.TemplateResponse(
        "fragments/sessio/live/start.html",
        {
            "request": request,
            "session": session,
        },
        headers={
            "HX-Trigger": "reload-marquee"
        }
    )
