"""This module holds the filters for the ``api`` module of ``photostories`` app"""

from django.shortcuts import get_object_or_404

from django_filters.filters import CharFilter

from rest_framework import filters

from mtp.apps.photostories.models import Photostory
from mtp.apps.trainings.models.sessions import TrainingSession


class PhotostoryFilter(filters.FilterSet):
    """Filter photostory by session

    Attributes
    ----------
    session: ``django_filters.CharFilter``
        The filter for session field

    """

    session = CharFilter(method='filter_session')

    def filter_session(self, queryset, name, value):  # pylint: disable=unused-argument
        """Filter on session

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

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

        """

        if value:
            session = get_object_or_404(
                TrainingSession,
                pk=value
            )

            return queryset.for_session(session)

        return queryset

    class Meta:
        model = Photostory
        fields = ['session']
