__author__ = 'christian'

from datetime import date

from django.db import models


class HanchanManager(models.Manager):
    use_for_related_fields = True

    def confirmed_hanchans(self, user=None, **kwargs):
        if user:
            return self.user_hanchans(user, confirmed=True, **kwargs)
        else:
            return self.filter(confirmed=True, **kwargs)

    def dan_hanchans(self, user, **kwargs):
        queryset = self.filter(
            models.Q(player1=user, player1_dan_points__isnull=False) |
            models.Q(player2=user, player2_dan_points__isnull=False) |
            models.Q(player3=user, player3_dan_points__isnull=False) |
            models.Q(player4=user, player4_dan_points__isnull=False)
        ).filter(confirmed=True, **kwargs)
        queryset = queryset.select_related().order_by('-start')
        for hanchan in queryset:
            hanchan.get_playerdata(user)
        return queryset

    def kyu_hanchans(self, user, **kwargs):
        queryset = self.filter(
            models.Q(player1=user, player1_kyu_points__isnull=False) |
            models.Q(player2=user, player2_kyu_points__isnull=False) |
            models.Q(player3=user, player3_kyu_points__isnull=False) |
            models.Q(player4=user, player4_kyu_points__isnull=False)
        ).filter(confirmed=True, **kwargs)
        queryset = queryset.select_related().order_by('-start')
        for hanchan in queryset:
            hanchan.get_playerdata(user)
        return queryset

    def season_hanchans(self, user=None, season=None):
        season = season or date.today().year
        return self.confirmed_hanchans(user=user, season=season)

    def user_hanchans(self, user, **kwargs):
        queryset = self.filter(
            models.Q(player1=user) | models.Q(player2=user) |
            models.Q(player3=user) | models.Q(player4=user)
        )
        queryset = queryset.select_related().order_by('-start')
        if kwargs:
            queryset = queryset.filter(**kwargs)
        for hanchan in queryset:
            hanchan.get_playerdata(user)
        return queryset

    def hanchan_stats(self, queryset=None):
        queryset = queryset or self.get_query_set()
        self.num_hanchans = queryset.count()
        self.won_hanchans = queryset.filter(placement=1).count()
        self.good_hanchans = queryset.filter(placement__lt=3).count()

    def unconfirmed_hanchans(self, user=None, **kwargs):
        if user:
            return self.user_hanchans(user, confirmed=False, **kwargs)
        else:
            return self.filter(confirmed=False, **kwargs)


class SeasonRankingManager(models.Manager):

    def current_rankings(self):
        current_season = date.today().year
        return self.filter(season=current_season)

    @property
    def season_list(self):
        values_list = self.model.objects.values_list('season', flat=True)
        return values_list.order_by('season').distinct()
