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

from django.contrib import admin
from django.db.models import Count
from django.utils.translation import ugettext_lazy as _


class SimpleBooleanListFilter(admin.SimpleListFilter):

    def lookups(self, request, model_admin):
        return (('yes', _('yes')),
                ('no', _('no ')))


class HasAwardBonus(SimpleBooleanListFilter):
    title = _('has award bonus')
    parameter_name = 'bonus'

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            return queryset.exclude(award_bonus__isnull=True)
        elif self.value() == 'no':
            return queryset.filter(award_bonus__isnull=True)


class ReporterRewardsFilter(SimpleBooleanListFilter):
    title = _('has rewards')
    parameter_name = 'has_rewards'

    def queryset(self, request, queryset):
        if self.value() is not None:
            if self.value() == 'yes':
                return queryset.exclude(rewards__isnull=True)
            elif self.value() == 'no':
                return queryset.filter(rewards__isnull=True)


class RewardReporterLinkFilter(SimpleBooleanListFilter):
    title = _('has reporter')
    parameter_name = 'has_reporter'

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            return queryset.exclude(reporter__isnull=True)
        elif self.value() == 'no':
            return queryset.filter(reporter__isnull=True)


class DuplicateMembership(SimpleBooleanListFilter):
    title = _('double membership')
    parameter_name = 'double'

    def queryset(self, request, queryset):
        duplicates = list(self.get_duplicates(queryset))
        if self.value() == 'yes':
            return queryset.filter(id__in=duplicates)
        elif self.value() == 'no':
            return queryset.exclude(id__in=duplicates)

    def get_duplicates(self, queryset):
        unique_values = queryset.values('user', 'list')
        counted_values = unique_values.annotate(Count('id'))
        filtered_values = counted_values.filter(id__count__gt=1)
        for kwargs in filtered_values.values('user', 'list'):
            for membership_id in queryset.filter(**kwargs).values_list('id', flat=True):
                yield membership_id
