from django import forms
from django.forms.widgets import TextInput

from .utils import get_icons


class NummiFileInput(forms.ClearableFileInput):
    template_name = "main/form/fileinput.html"


class NummiForm(forms.ModelForm):
    template_name = "main/form/form_base.html"
    meta_fieldsets = []

    def __init__(self, *args, **kwargs):
        kwargs.pop("user", None)
        super().__init__(*args, **kwargs)

    @property
    def fieldsets(self):
        if self.meta_fieldsets:
            for group in self.meta_fieldsets:
                yield ((self[f] for f in fieldset) for fieldset in group)
        else:
            yield ([f] for f in self)


class DatalistInput(TextInput):
    template_name = "main/forms/widgets/datalist.html"

    def __init__(self, *args, options=[]):
        self.options = options
        super().__init__(*args)

    def get_context(self, *args):
        context = super().get_context(*args)
        name = context["widget"]["name"]
        context["widget"]["attrs"]["list"] = f"{name}-list"
        context["widget"]["attrs"]["autocomplete"] = "off"
        context["widget"]["options"] = self.options
        return context


class IconInput(DatalistInput):
    template_name = "main/forms/widgets/icon.html"
    icon_list = get_icons()

    def get_context(self, *args):
        context = super().get_context(*args)
        context["widget"]["options"] = self.icon_list
        return context
