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

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


class ShareableTableFilterMixin(django_filters.FilterSet):
    """ A mixin for AbstractTableFilter

    Specialized on filtering shareable model types

    """
    sa = django_filters.BooleanFilter(
        method='filter_show_all',
        label=_("Show unshared"),
        label_suffix=_(""),
        widget=forms.CheckboxInput(
            attrs={
                "class": "form-check-input",
                "title": _("If activated also shows entries which are not shared with you"),
            }
        )
    )

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user", None)
        if self.user is None:
            raise AttributeError("User must be set for further filtering!")
        super().__init__(*args, **kwargs)

    def filter_show_all(self, queryset, name, value) -> QuerySet:
        """ Filters queryset depending on value of 'show_all' setting

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

        Returns:

        """
        if not value:
            user_teams = self.user.shared_teams
            result = queryset.filter(
                Q(users__in=[self.user]) |  # requesting user has access
                Q(teams__in=user_teams)
            ).distinct()
            return result
        else:
            return queryset