import dataclasses
from typing import Annotated

from fastapi import HTTPException, Request
from fastapi.params import Form
from fastapi.responses import HTMLResponse
from folkugat_web.api.router import get_router
from folkugat_web.fragments.tema import properties as properties_fragments
from folkugat_web.model import temes as model
from folkugat_web.services import auth
from folkugat_web.services.temes import properties as properties_service

router = get_router()


@router.get("/api/tema/{tema_id}/property/{property_id}")
def property_(request: Request, logged_in: auth.LoggedIn, tema_id: int, property_id: int):
    property = properties_service.get_property_by_id(property_id=property_id, tema_id=tema_id)
    if not property:
        raise HTTPException(status_code=404, detail="Could not find lyric!")
    return properties_fragments.property_(request=request, logged_in=logged_in, property=property)


@router.put("/api/tema/{tema_id}/property/{property_id}")
def set_property(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    property_id: int,
    field: Annotated[model.PropertyField, Form()],
    value: Annotated[str, Form()],
):
    property = properties_service.get_property_by_id(property_id=property_id, tema_id=tema_id)
    if not property:
        raise HTTPException(status_code=404, detail="Could not find lyric!")
    new_property = dataclasses.replace(property, field=field, value=value.strip())
    properties_service.update_property(property=new_property)
    return properties_fragments.property_(request=request, logged_in=logged_in, property=new_property)


@router.post("/api/tema/{tema_id}/property")
def add_property(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
):
    property = properties_service.create_property(tema_id=tema_id)
    return properties_fragments.property_editor(
        request=request,
        logged_in=logged_in,
        property=property,
    )


@router.delete("/api/tema/{tema_id}/property/{property_id}")
def delete_property(_: auth.RequireLogin, tema_id: int, property_id: int):
    properties_service.delete_property(property_id=property_id, tema_id=tema_id)
    return HTMLResponse()


@router.get("/api/tema/{tema_id}/editor/property/{property_id}")
def property_editor(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    property_id: int,
):
    property = properties_service.get_property_by_id(property_id=property_id, tema_id=tema_id)
    if not property:
        raise HTTPException(status_code=404, detail="Could not find lyric!")
    return properties_fragments.property_editor(
        request=request,
        logged_in=logged_in,
        property=property,
    )
