# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib.admin import SimpleListFilter
from django.db.models import Q,F
import datetime


class OfferSubscriptionTerminationFilter(SimpleListFilter):
    title = 'Abonnement'
    parameter_name = 'termination'

    def lookups(self, request, model_admin):
        return (
            ('not_terminated', 'Abonnements en cours'),
            ('terminated', 'Abonnements résiliés'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'not_terminated':
            return queryset.filter(Q(resign_date__gt=datetime.date.today) | Q(resign_date__isnull=True))
        if self.value() == 'terminated':
            return queryset.filter(resign_date__lte=datetime.date.today)


class OfferSubscriptionCommitmentFilter(SimpleListFilter):
    title = 'Engagement'
    parameter_name = 'commitment'

    def lookups(self, request, model_admin):
        return (
            ('committed', 'Est engagé'),
            ('not_committed', 'N\'est plus engagé'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'committed':
            # TODO : Faire mieux que du SQL écrit en dur. La ligne 
            # en dessous ne fonctionne pas et je ne sais pas pourquoi
            return queryset.extra(where = ["subscription_date + INTERVAL '1 month' * commitment > current_date"])
            #~ return queryset.filter(subscription_date__gte=datetime.date.today - relativedelta(months=F('commitment'))) 
        if self.value() == 'not_committed':
            return queryset.extra(where = ["subscription_date + INTERVAL '1 month' * commitment <= current_date"])
            #~ return queryset.filter(subscription_date__lte=datetime.date.today - relativedelta(months=F('commitment'))) 

