from django.utils.functional import cached_property

from servala.frontend.forms.renderers import InlineFormRenderer


class HtmxMixin:
    """
    Form mixin that retains only a single field when specified.
    Useful when sending single fields with htmx.
    """

    def __init__(self, *args, **kwargs):
        self.single_field = kwargs.pop("single_field", None)

        super().__init__(*args, **kwargs)

        if self.single_field and self.single_field in self.fields:
            field = self.fields[self.single_field]
            self.fields.clear()
            self.fields[self.single_field] = field

    @cached_property
    def default_renderer(self):
        if self.single_field:
            return InlineFormRenderer
