# -*- coding: utf-8 -*-
"""
Created on 23.05.2011

@author: christian
"""
from django.core.cache import cache
from mahjong_ranking import models
from . import logger, MIN_HANCHANS_FOR_LADDER


class DenormalizationUpdateMiddleware(object):
    """
    This Class deferres the recalculation for the Otaku XP at the end of a
    response.
    """
    event_queue = set()
    season_queue = set()

    def process_response(self, request, response):
        # We only do this in POST request, to speedup the responsetime.
        if request.method == 'POST':
            queue = cache.get('event_ranking_queue', set())
            if len(queue) > 0:
                self.recalculate_event_rankings(queue)
                cache.set('event_ranking_queue', set(), 360)

            queue = cache.get('kyu_dan_ranking_queue', set())
            if len(queue) > 0:
                self.recalulate_kyu_dan_ranking(queue)
                cache.set('kyu_dan_ranking_queue', set(), 360)

            queue = cache.get('ladder_ranking_queue', set())
            if len(queue) > 0:
                self.recalculate_ladder_ranking(queue)
                cache.set('ladder_ranking_queue', set(), 360)

            for event_id in self.event_queue:
                self.update_event_placement()
            for season in self.season_queue:
                self.update_season_placements()



        return response

    def recalculate_event_rankings(self, queue):
        # recalculate tournament (event) rankings:
        for event_id, user_id in queue:
            logger.info("recalculate %d tournament Ranking in %s", user_id, event_id)
            ranking = models.EventRanking.objects.get_or_create(event_id=event_id, user_id=user_id)[0]
            ranking.recalculate()
            self.event_queue.add(event_id)
        return queue

    def recalulate_kyu_dan_ranking(self, queue):
        for user_id in queue:
            ranking = models.KyuDanRanking.objects.get_or_create(user_id=user_id)[0]
            ranking.recalculate()
        return queue

    def recalculate_ladder_ranking(self, queue):
        for season, user_id in queue:
            ladder = models.SeasonRanking.objects.get_or_create(user_id=user_id, season=season)[0]
            ladder.recalculate()
            self.season_queue.add(season)

    def update_event_placements(self):
        for event_id in self.event_queue:
            eventranking_set = models.EventRanking.objects.filter(event_id=event_id).order_by('avg_placement', '-avg_score')
            placement = 1
            for ranking in eventranking_set:
                ranking.placement = placement
                placement += 1
                ranking.save(force_update=True)

    def update_season_placements(self):
        for season in self.season_queue:
            logger.info(u'Recalculate placements for Season %d', season)
            season_rankings = models.SeasonRanking.objects.filter(
                season=season, hanchan_count__gt=MIN_HANCHANS_FOR_LADDER
            ).order_by('avg_placement', '-avg_score')
            placement = 1
            for ranking in season_rankings:
                ranking.placement = placement
                ranking.save(force_update=True)
                placement += 1
