from fastapi import HTTPException, Request
from folkugat_web.api.router import get_router
from folkugat_web.fragments import live
from folkugat_web.fragments.sessio import page as sessio
from folkugat_web.model.sessions import Session
from folkugat_web.services import auth
from folkugat_web.services import sessions as sessions_service
from folkugat_web.templates import templates

router = get_router()


def session_description(session: Session) -> str:
    date_names = sessions_service.get_date_names(session.date)
    date_str = f"{date_names.day_name} {date_names.day} {date_names.month_name} de {date_names.year}"
    location_str = f"A {session.venue.name}" if session.venue else ""
    time_str = f"de {session.start_time.strftime('%H:%M')} a {session.end_time.strftime('%H:%M')}"
    location_time_str = " ".join([location_str, time_str])
    if location_time_str:
        location_time_str = location_time_str[0].upper() + location_time_str[1:]
    notes_str = session.notes or ""
    return "\n".join(filter(bool, [
        date_str,
        location_time_str,
        notes_str,
    ]))


@router.get("/sessio/{session_id}")
def page(
    request: Request,
    logged_in: auth.LoggedIn,
    session_id: int,
):
    session = sessions_service.get_session(session_id=session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Could not find session")
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request,
            "page_title": "Folkugat - Sessió",
            "page_description": session_description(session),
            "page_card": session.cartell_url,
            "content": f"/api/content/sessio/{session_id}",
            "logged_in": logged_in,
        }
    )


@router.get("/api/content/sessio/{session_id}")
def contingut(
    request: Request,
    logged_in: auth.LoggedIn,
    session_id: int,
):
    return sessio.pagina(request, session_id, logged_in)


@router.put("/api/sessio/{session_id}/live")
def set_live(
    request: Request,
    _: auth.RequireLogin,
    session_id: int,
):
    return live.start_live_session(request=request, session_id=session_id)


@router.delete("/api/sessio/{session_id}/live")
def stop_live(
    request: Request,
    _: auth.RequireLogin,
    session_id: int,
):
    return live.stop_live_session(request=request, session_id=session_id)
