from typing import Optional

from fastapi import Request
from folkugat_web.model import temes as model
from folkugat_web.services.temes import query as temes_q
from folkugat_web.templates import templates


def title(request: Request, logged_in: bool, tema: Optional[model.Tema] = None, tema_id: Optional[int] = None):
    if tema is None:
        if tema_id is None:
            raise ValueError("Either 'tema' or 'tema_id' must be given!")
        tema = temes_q.get_tema_by_id(tema_id)
    return templates.TemplateResponse(
        "fragments/tema/title.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
        }
    )


def title_editor(request: Request, logged_in: bool, tema_id: int):
    tema = temes_q.get_tema_by_id(tema_id)
    return templates.TemplateResponse(
        "fragments/tema/editor/title.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
        }
    )


def lyric(request: Request, logged_in: bool, tema_id: int, lyric_idx: int):
    tema = temes_q.get_tema_by_id(tema_id)
    if tema is None:
        raise ValueError(f"No tune exists for tema_id: {tema_id}")
    if len(tema.lyrics) < lyric_idx:
        raise ValueError(f'Lyric index out of bounds')
    lyric = tema.lyrics[lyric_idx]

    return templates.TemplateResponse(
        "fragments/tema/lyric.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
            "lyric_idx": lyric_idx,
            "lyric": lyric,
        }
    )


def lyric_editor(request: Request, logged_in: bool, tema_id: int, lyric_idx: int):
    tema = temes_q.get_tema_by_id(tema_id)
    if tema is None:
        raise ValueError(f"No tune exists for tema_id: {tema_id}")
    if len(tema.lyrics) < lyric_idx:
        raise ValueError(f'Lyric index out of bounds')
    lyric = tema.lyrics[lyric_idx]

    return templates.TemplateResponse(
        "fragments/tema/editor/lyric.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
            "lyric_idx": lyric_idx,
            "lyric": lyric,
        }
    )
