"""This module holds the filters for the ``accounts`` app"""

from django.db.models import Q
from django.utils.translation import ugettext_lazy as _

import django_filters

from .constants import INTERNAL_GROUP_TRAINEE, INTERNAL_GROUP_TRAINER
from .models import Group, MTPUser


class MTPUserFilterSet(django_filters.FilterSet):
    """FilterSet for the ``MTPUser`` list view"""

    IS_DELETED_CHOICES = (
        ('', _('All')),
        (0, _('Active')),
        (1, _('Inactive')),
    )

    mgroups = django_filters.ModelMultipleChoiceFilter(
        label=_('Group'),
        queryset=Group.objects.filter(name__in=[INTERNAL_GROUP_TRAINEE, INTERNAL_GROUP_TRAINER]),
    )
    search = django_filters.CharFilter(
        method='search_filter',
        label=_('Search')
    )
    is_deleted = django_filters.ChoiceFilter(
        label=_('Is Active'),
        choices=IS_DELETED_CHOICES,
    )

    class Meta:
        model = MTPUser
        fields = ['is_deleted']

    def search_filter(self, queryset, name, value):  # pylint: disable=unused-argument
        """Filter using multiple fields

        Parameters
        ----------
        For the parameters, see ``django_filters.Filter`` (``method`` attribute)

        Returns
        -------
        Queryset
            A clone of the queryset passed in parameters, filtered.

        """

        return queryset.filter(
            Q(username__icontains=value) |
            Q(first_name__icontains=value) |
            Q(last_name__icontains=value) |
            Q(email__icontains=value)
        )
