from fastapi import HTTPException, 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: model.Tema | None = None, tema_id: int | None = 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)
        if not tema:
            raise HTTPException(status_code=404, detail="Could not find tune")
    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)
    if not tema:
        raise HTTPException(status_code=404, detail="Could not find tune")
    return templates.TemplateResponse(
        "fragments/tema/editor/title.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
        }
    )


def property_(request: Request, logged_in: bool, tema_id: int, property_id: int):
    tema = temes_q.get_tema_by_id(tema_id)
    if not tema:
        raise HTTPException(status_code=404, detail="Could not find tune")
    prop = tema.properties.get(property_id)

    return templates.TemplateResponse(
        "fragments/tema/property.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
            "property_id": property_id,
            "property": prop,
            "PropertyField": model.PropertyField,
        }
    )


def property_editor(request: Request, logged_in: bool, tema_id: int, property_id: int):
    tema = temes_q.get_tema_by_id(tema_id)
    if not tema:
        raise HTTPException(status_code=404, detail="Could not find tune")
    prop = tema.properties.get(property_id)

    return templates.TemplateResponse(
        "fragments/tema/editor/property.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
            "property_id": property_id,
            "property": prop,
            "PropertyField": model.PropertyField,
        }
    )


def visibility(request: Request, logged_in: bool, tema: model.Tema):
    return templates.TemplateResponse(
        "fragments/tema/visibility.html",
        {
            "request": request,
            "logged_in": logged_in,
            "tema": tema,
        }
    )
