# -*- coding: utf-8 -*-
import django_filters

from events.rest_framework_contrib.queryset_filters import NumberInFilter
from events.surveyme_integration.models import (
    SurveyHook,
    ServiceSurveyHookSubscription,
    IntegrationFileTemplate,
    HookSubscriptionNotification,
)
from events.surveyme.api_admin.v2.filters import SurveyFilterBackend


class SurveyHookFilter(django_filters.FilterSet):
    survey = django_filters.CharFilter(field_name='survey', lookup_expr='exact')

    class Meta:
        model = SurveyHook
        fields = (
            'survey',
        )


class ServiceSurveyHookSubscriptionFilter(django_filters.FilterSet):
    id__in = NumberInFilter(field_name='id', lookup_expr='in')

    class Meta:
        model = ServiceSurveyHookSubscription
        fields = (
            'id',
        )


class IntegrationFileTemplateFilter(django_filters.FilterSet):
    survey = django_filters.CharFilter(field_name='survey', lookup_expr='exact')

    class Meta:
        model = IntegrationFileTemplate
        fields = (
            'survey',
        )


def boolean_filter(qs, name, value):
    if value.lower() in ('false', '0'):
        value = False
    elif value.lower() in ('true', '1'):
        value = True
    else:
        value = None
    if value is not None:
        qs = qs.filter(**{name: value})
    return qs


class HookSubscriptionNotificationFilter(django_filters.FilterSet):
    survey = django_filters.Filter(field_name='survey_id')
    survey_id = django_filters.Filter(field_name='survey_id')
    survey_group_id = django_filters.Filter(field_name='survey_group_id')
    subscription_id = django_filters.Filter(field_name='subscription_id')
    subscription = django_filters.Filter(field_name='subscription_id')
    profile = django_filters.Filter(field_name='user_id')
    notification_id = django_filters.Filter(field_name='notification_id')
    notification = django_filters.Filter(field_name='notification_id')
    is_visible = django_filters.Filter(method=boolean_filter)
    date_created__gt = django_filters.IsoDateTimeFilter(field_name='date_created', lookup_expr='gt')
    date_created__lt = django_filters.IsoDateTimeFilter(field_name='date_created', lookup_expr='lt')
    id__in = NumberInFilter(field_name='id', lookup_expr='in')

    ordering = django_filters.OrderingFilter(fields=(
        ('date_created', 'date_created'),
        ('date_updated', 'date_updated'),
    ))

    class Meta:
        model = HookSubscriptionNotification
        fields = (
            'id',
            'status',
            'date_created',
        )


class HookSubscriptionNotificationFilterBackend(SurveyFilterBackend):
    def _filter_queryset(self, request, queryset, view):
        from events.surveyme.models import Survey
        survey_qs = super()._filter_queryset(request, Survey.objects.all(), view)
        return queryset.filter(survey__in=survey_qs)
