from django import forms
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from wagtail.admin.forms import WagtailAdminModelForm
from wagtail.admin.forms.choosers import BaseFilterForm
from wagtail.admin.ui.tables import UpdatedAtColumn
from wagtail.admin.views.generic.chooser import ChooseResultsView, ChooseView
from wagtail.admin.viewsets.chooser import ChooserViewSet
from wagtail.snippets.views.snippets import SnippetViewSet

from dnscms.utils import slugify
from events.models import EventOrganizer


class EventOrganizerSearchForm(BaseFilterForm):
    """Substring search on name/slug"""

    q = forms.CharField(
        label=_("Search term"),
        widget=forms.TextInput(attrs={"placeholder": _("Search")}),
        required=False,
    )

    def filter(self, objects):
        objects = super().filter(objects)
        search_query = self.cleaned_data.get("q")
        if search_query:
            objects = objects.filter(
                Q(name__icontains=search_query) | Q(slug__icontains=search_query)
            )
            self.is_searching = True
            self.search_query = search_query
        return objects


class EventOrganizerChooseView(ChooseView):
    filter_form_class = EventOrganizerSearchForm


class EventOrganizerChooseResultsView(ChooseResultsView):
    filter_form_class = EventOrganizerSearchForm


class EventOrganizerSnippetViewSet(SnippetViewSet):
    model = EventOrganizer
    icon = "group"
    list_display = ["name", "slug", UpdatedAtColumn()]
    # unset the search backend so the listing search filters on icontains instead
    search_backend_name = None
    search_fields = ["name", "slug"]


class EventOrganizerCreationForm(WagtailAdminModelForm):
    class Meta:
        model = EventOrganizer
        fields = ["name", "association", "external_url"]

    def save(self, commit=True):
        instance = super().save(commit=False)
        if not instance.slug:
            instance.slug = slugify(instance.name)
        if commit:
            instance.save()
        return instance


class EventOrganizerChooserViewSet(ChooserViewSet):
    model = "events.EventOrganizer"
    icon = "group"
    per_page = 30
    page_title = _("Choose organizers")
    choose_one_text = _("Choose an organizer")
    choose_another_text = _("Choose another organizer")
    edit_item_text = _("Edit this organizer")
    creation_form_class = EventOrganizerCreationForm
    choose_view_class = EventOrganizerChooseView
    choose_results_view_class = EventOrganizerChooseResultsView


event_organizer_chooser_viewset = EventOrganizerChooserViewSet("event_organizer_chooser")
