# -*- encoding: utf-8 -*-
"""
Created on 22.11.2014

@author: christian
"""
from django.db import models

from . import settings


class GameManager(models.Manager):
    use_for_related_fields = True

    def player_games(self, player, season=None, **kwargs):
        queryset = self.filter(
            models.Q(player1=player) | models.Q(player2=player) |
            models.Q(player3=player) | models.Q(player4=player) |
            models.Q(player5=player) | models.Q(player6=player)
        )
        if season:
            queryset = queryset.filter(season=season)
        if kwargs:
            queryset = queryset.filter(**kwargs)
        return queryset


class LadderManager(models.Manager):
    use_for_related_fields = True

    def calculate_rankings(self, season):
        """
        Berechnet die Jahresrankings für die Spieler neu.
        @param season: Das Jahr das neu berechnet werden soll
        @type season: Integer
        """
        rankings = self.filter(season=season)
        rankings.update(placement=None)
        rankings = rankings.filter(
            games_count__gte=settings.MAISTAR_GAMES_FOR_LADDERRANKING)  # @IgnorePep8
        rankings = rankings.order_by('avg_placement', '-avg_score')
        placement = 1
        previous_avg_placement = None
        previous_avg_score = None
        previous_placement = None
        for ranking in rankings:
            if ranking.avg_placement == previous_avg_placement \
                    and ranking.avg_score == previous_avg_score:
                ranking.placement = previous_placement
            else:
                ranking.placement = placement
            ranking.save(force_update=True)
            previous_avg_placement = ranking.avg_placement
            previous_avg_score = ranking.avg_score
            previous_placement = ranking.placement
            placement += 1

    def get_seasons(self):
        return self.values_list('season', flat=True).order_by(
            'season').distinct()
