import django_filters as filters
from django.utils.translation import gettext_lazy as _

from . import models


__all__ = (
    "PageFilters",
    "EpisodeFilters",
    "ImageFilterSet",
    "SoundFilterSet",
    "TrackFilterSet",
)


class PageFilters(filters.FilterSet):
    q = filters.CharFilter(method="search_filter", label=_("Search"))

    class Meta:
        model = models.Page
        fields = {
            "category__id": ["in", "exact"],
            "pub_date": ["exact", "gte", "lte"],
        }

    def search_filter(self, queryset, name, value):
        return queryset.search(value)


class EpisodeFilters(PageFilters):
    podcast = filters.BooleanFilter(method="podcast_filter", label=_("Podcast"))

    class Meta:
        model = models.Episode
        fields = PageFilters.Meta.fields.copy()

    def podcast_filter(self, queryset, name, value):
        if value:
            return queryset.filter(sound__is_public=True).distinct()
        return queryset.filter(sound__isnull=True)


class ImageFilterSet(filters.FilterSet):
    search = filters.CharFilter(field_name="search", method="search_filter")

    def search_filter(self, queryset, name, value):
        return queryset.filter(original_filename__icontains=value)


class SoundFilterSet(filters.FilterSet):
    station = filters.NumberFilter(field_name="program__station__id")
    program = filters.NumberFilter(field_name="program_id")
    # episode = filters.NumberFilter(field_name="episode_id")
    search = filters.CharFilter(field_name="search", method="search_filter")

    class Meta:
        model = models.Sound
        fields = {
            #    "episode": ["in", "exact", "isnull"],
        }

    def search_filter(self, queryset, name, value):
        return queryset.search(value)


class TrackFilterSet(filters.FilterSet):
    artist = filters.CharFilter(field_name="artist", lookup_expr="icontains")
    album = filters.CharFilter(field_name="album", lookup_expr="icontains")
    title = filters.CharFilter(field_name="title", lookup_expr="icontains")
