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

"""
import django_filters
from django import forms
from django.db.models import QuerySet, Q
from django.utils.translation import gettext_lazy as _


class UserLoggedTableFilterMixin(django_filters.FilterSet):
    ul = django_filters.CharFilter(
        method="filter_user_log",
        label=_(""),
        label_suffix=_(""),
        widget=forms.TextInput(
            attrs={
                "placeholder": _("Logged user"),
                "title": _("Search for entries where this person has been participated according to log history"),
                "class": "form-control",
            }
        ),
    )

    class Meta:
        abstract = True

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

        Args:
            queryset (QuerySet): Incoming (prefiltered) queryset
            name (str): Name of input field
            value (str): Value of input field

        Returns:

        """
        value = value.replace(",", " ")
        value = value.strip()
        values = value.split(" ")

        q = Q()
        for val in values:
            q &= (
                    Q(log__user__username__icontains=val) |
                    Q(log__user__first_name__icontains=val) |
                    Q(log__user__last_name__icontains=val)
            )

        queryset = queryset.filter(q)
        return queryset
