from collections.abc import Iterable, Iterator

from folkugat_web.dal.sql.temes import properties as properties_dal
from folkugat_web.model import temes as model


def add_properties_to_tema(tema: model.Tema) -> model.Tema:
    if tema.id is not None:
        tema.properties = list(properties_dal.get_properties(tema_id=tema.id))
    return tema


def add_properties_to_temes(temes: Iterable[model.Tema]) -> Iterator[model.Tema]:
    return map(add_properties_to_tema, temes)


def get_property_by_id(property_id: int, tema_id: int | None = None) -> model.Property | None:
    return next(iter(properties_dal.get_properties(property_id=property_id, tema_id=tema_id)), None)


def update_property(property: model.Property):
    properties_dal.update_property(property=property)


def delete_property(property_id: int, tema_id: int | None = None):
    properties_dal.delete_property(property_id=property_id, tema_id=tema_id)


def create_property(tema_id: int) -> model.Property:
    return properties_dal.create_property(tema_id=tema_id)
