"""This module holds the filters and the filters-related forms for the ``assessments`` app"""

from django.utils.translation import ugettext_lazy as _

import django_filters
from form_utils.forms import BetterForm

from mtp.apps.common.widgets import DateRangeInput

from .models import CertificationProgramUserStatus, CertificationStatus


class CertificationResultsFilterForm(BetterForm):
    """Form for the ``CertificationResultsFilter`` filter

    Notes
    -----
    This form is only used to define the fieldsets.

    """

    class Meta:
        fieldsets = [
            (_('Filters'), {
                'fields': [
                    'status',
                    'user__last_name',
                    'session__start_date',
                    'is_validated'
                ]
            }),
            (_('Order'), {
                'fields': ['o']
            })
        ]


class CertificationResultsFilter(django_filters.FilterSet):
    """Filter class for the ``CertificationResults`` list view

    Attributes
    ----------
    session__start_date: ``django_filters.DateFromToRangeFilter``
        Filter field for the date the trainee obtained the certification
    status: ``django_filters.ModelChoiceFilter``
        Filter field for the status obtained by the trainee
    user__last_name: ``django_filters.CharFilter``
        Filter field for the last name of the trainee
    is_validated: ``django_filters.BooleanFilter``
        Filter the validation status of the certification

    """

    session__start_date = django_filters.DateFromToRangeFilter(
        label=_('Date'),
        widget=DateRangeInput()
    )
    status = django_filters.ModelChoiceFilter(
        label=_('Certification status'),
        empty_label=_('All statuses'),
    )
    user__last_name = django_filters.CharFilter(
        label=_('Last name'),
        lookup_type='icontains'
    )
    is_validated = django_filters.BooleanFilter(
        label=_('Addressed'),
    )

    class Meta:
        model = CertificationProgramUserStatus
        fields = ['status', 'user__last_name', 'session__start_date', 'is_validated']
        order_by = (
            ('-session__start_date', _('Date')),
            ('-score', _('Score'))
        )
        form = CertificationResultsFilterForm

    def __init__(self, *args, **kwargs):
        """Update the filters accordingly to the provided kwargs

        Provide a filtered queryset of the ``status`` field to display only available status.

        """

        competency_tree = kwargs.pop('competency_tree')

        super().__init__(*args, **kwargs)

        self.filters['status'].extra.update({
            'queryset': CertificationStatus.objects.non_deleted().filter(
                program__tree=competency_tree
            )
        })
