"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: ksp-servicestelle@sgdnord.rlp.de
Created on: 18.08.22

"""
import django_filters
from django.db.models import QuerySet, Q

from intervention.inputs import DummyFilterInput


class KeywordTableFilterMixin(django_filters.FilterSet):
    q = django_filters.Filter(
        method='filter_by_keyword',
        # Since we use a custom search bar in the template, we need to 'render' this filter
        # as 'anonymous' HiddenInput (no id, no name). This way our custom search bar's id and name won't be
        # overwritten with these id and name (which would be equal)
        # This way we can use the simple filter method mapping for a parameter without using a predefined widget!
        widget=DummyFilterInput(),
    )

    class Meta:
        abstract = True

    def filter_by_keyword(self, queryset, name, value) -> QuerySet:
        """ Filters queryset depending on value of search bar input

        Args:
            queryset ():
            name ():
            value ():

        Returns:

        """
        value = value.strip()
        value = value.split(" ")
        # build filter expression
        q = Q()
        for val in value:
            q &= Q(title__icontains=val) | Q(identifier__icontains=val)
        return queryset.filter(q)
