from django.db.models import Model
from django.forms import widgets
from accrete.contrib import ui


class Filter(widgets.TextInput):
    template_name = 'ui/widgets/filter.html'
    input_type = 'text'

    def __init__(
        self,
        model: Model | type[Model],
        default_lookup: str | None = None,
        attrs: dict | None = None,
    ):
        super().__init__(attrs)
        self.model = model
        self.default_lookup = default_lookup

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        ui_filter = ui.Filter(
            model=self.model,
            query_dict={'q': value or '[]'},
            default_lookup=self.default_lookup,
            autofocus=False,
        )
        context.update(ui_filter=ui_filter)
        return context
