from typing import Annotated

from fastapi import Request
from fastapi.params import Form
from fastapi.responses import HTMLResponse
from folkugat_web.api import router
from folkugat_web.fragments import tema, temes
from folkugat_web.model import temes as model
from folkugat_web.services import auth
from folkugat_web.services.temes import write as temes_w
from folkugat_web.templates import templates


@router.get("/tema/{tema_id}")
def page(request: Request, logged_in: auth.LoggedIn, tema_id: int):
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request,
            "page_title": "Folkugat",
            "content": f"/api/tema/{tema_id}",
            "logged_in": logged_in,
        }
    )


@router.get("/api/tema/{tema_id}")
def contingut(request: Request, logged_in: auth.LoggedIn, tema_id: int):
    return temes.tema(request, tema_id, logged_in)


@router.get("/api/tema/{tema_id}/title")
def title(request: Request, logged_in: auth.LoggedIn, tema_id: int):
    return tema.title(request=request, tema_id=tema_id, logged_in=logged_in)


@router.put("/api/tema/{tema_id}/title")
def set_title(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    title: Annotated[str, Form()],
):
    new_tema = temes_w.update_title(tema_id=tema_id, title=title)
    return tema.title(request=request, tema=new_tema, logged_in=logged_in)


@router.get("/api/tema/{tema_id}/lyric/{lyric_idx}")
def lyric(request: Request, logged_in: auth.LoggedIn, tema_id: int, lyric_idx: int):
    return tema.lyric(request=request, logged_in=logged_in, tema_id=tema_id, lyric_idx=lyric_idx)


@router.put("/api/tema/{tema_id}/lyric/{lyric_idx}")
def set_lyric(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    lyric_idx: int,
    title: Annotated[str, Form()],
    lyric: Annotated[str, Form()],
):
    new_lyric = model.Lyrics(title=title, content=lyric.strip())
    temes_w.update_lyric(tema_id=tema_id, lyric_idx=lyric_idx, lyric=new_lyric)
    return tema.lyric(request=request, logged_in=logged_in, tema_id=tema_id, lyric_idx=lyric_idx)


@router.post("/api/tema/{tema_id}/lyric")
def add_lyric(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
):
    new_tema = temes_w.add_lyric(tema_id=tema_id)
    lyric_idx = len(new_tema.lyrics) - 1
    return tema.lyric_editor(request=request, logged_in=logged_in, tema_id=tema_id, lyric_idx=lyric_idx)


@router.delete("/api/tema/{tema_id}/lyric/{lyric_idx}")
def delete_lyric(
    tema_id: int,
    lyric_idx: int,
):
    temes_w.delete_lyric(tema_id=tema_id, lyric_idx=lyric_idx)
    return HTMLResponse()
