# Path: ladder/models.py
# class Season(models.Model):
#     name = models.CharField(max_length=150)
#     start_date = models.DateField('Start date')
#     end_date = models.DateField('End date')
#     season_round = models.IntegerField()
# 
#     class Meta:
#         ordering = ['-start_date',]
# 
#     def __str__(self):
#         return str(self.start_date.year) + ' Round ' + str(self.season_round)
# 
#     def get_stats(self):
#         """
#         Generates the season stats
#         """
#         player_count = 0
#         results_count = 0
#         total_games_count = 0.0
#         for ladder in self.ladder_set.all():
#             player_count += ladder.league_set.count()
#             results_count += ladder.result_set.count() / 2
#             total_games_count += (ladder.league_set.count() * (ladder.league_set.count() - 1)) / 2
# 
#         percentage_played = (results_count / total_games_count) * 100
# 
#         return {
#             'divisions': self.ladder_set.count(),
#             'percentage_played': "{0:.2f}".format(percentage_played),
#             'total_games_count': total_games_count,
#             'results_count': results_count,
#             'player_count': player_count
#         }
# 
#     def get_leader_stats(self, user):
#         """
#         Generates the list of leaders for current season
#         """
#         current_leaders = {}
# 
#         for ladder in self.ladder_set.all():
#             current_leaders[ladder.id] = ladder.get_leader(user=user)
# 
#         return {
#             'current_leaders': current_leaders,
#         }
# 
#     def get_progress(self):
#         """
#         Query how many games have been played so far.
#         """
#         results = Result.objects.raw("""
#             SELECT ladder_result.id, ladder_id, season_id, date_added, COUNT(*) AS added_count
#             FROM ladder_result LEFT JOIN ladder_ladder
#             ON ladder_result.ladder_id=ladder_ladder.id
#             WHERE season_id = %s GROUP BY DATE(date_added)
#             ORDER BY DATE(date_added) ASC;
#         """, [self.id])
# 
#         leagues = League.objects.raw("""
#             SELECT ladder_league.id, COUNT(*) AS player_count
#             FROM ladder_league LEFT JOIN ladder_ladder
#             ON ladder_league.ladder_id=ladder_ladder.id
#             WHERE season_id = %s GROUP BY ladder_id;
#         """, [self.id])
# 
#         played = []
#         played_days = []
#         played_cumulative = []
#         played_cumulative_count = 0
#         latest_result = False
# 
#         for result in results:
#             played.append(result.added_count)
#             played_days.append((result.date_added - self.start_date).days)
# 
#             played_cumulative_count += result.added_count / 2
#             played_cumulative.append(played_cumulative_count)
#             latest_result = result.date_added
# 
#         total_matches = 0
#         for league in leagues:
#             total_matches += (league.player_count-1) * league.player_count / 2
# 
#         return {
#             "season_days": [0, (self.end_date - self.start_date).days],
#             "season_total_matches": [0, total_matches],
#             "played_days": played_days,
#             "played": played,
#             "played_cumulative": played_cumulative,
#             "latest_result": latest_result.strftime("%B %d, %Y") if latest_result else "-"
#         }
# 
# Path: ladder/views.py
# @cache_page(60 * 60, key_prefix='season')  # 1 hour page cache
# def season(request, year, season_round):
#     season_object = get_object_or_404(Season, start_date__year=year, season_round=season_round)
# 
#     ladders = Ladder.objects.filter(season=season_object)
# 
#     results = Result.objects.filter(ladder__season=season_object)
#     league = League.objects.filter(ladder__season=season_object)
# 
#     results_dict = {}
# 
#     for result in results:
#         results_dict.setdefault(result.player.id, []).append(result)
# 
#     return render(
#         request, 'ladder/season/index.html',
#         dict(season=season_object, ladders=ladders, results_dict=results_dict, league=league)
#     )


from django.core.management.base import BaseCommand, CommandError
from django.test.client import RequestFactory
from django.conf import settings
from django.urls import reverse
from ladder.models import Season
from ladder.views import season as season_view



class Command(BaseCommand):
    help = 'Refreshes cached pages'

    def handle(self, *args, **options):
        """
        Script that calls all season pages to refresh the cache on them if it has expired.

        Any time/date settings create postfixes on the caching key, for now the solution is to disable them.
        """

        if settings.USE_I18N:
            raise CommandError('USE_I18N in settings must be disabled.')

        if settings.USE_L10N:
            raise CommandError('USE_L10N in settings must be disabled.')

        if settings.USE_TZ:
            raise CommandError('USE_TZ in settings must be disabled.')

        self.factory = RequestFactory()
        seasons = Season.objects.all()
        for season in seasons:
            path = reverse('ladder:season', args=(str(season.end_date.year), str(season.season_round)))
            # use the request factory to generate the correct url for the cache hash
            request = self.factory.get(path)


# Path: ladder/models.py
# class Season(models.Model):
#     name = models.CharField(max_length=150)
#     start_date = models.DateField('Start date')
#     end_date = models.DateField('End date')
#     season_round = models.IntegerField()
# 
#     class Meta:
#         ordering = ['-start_date',]
# 
#     def __str__(self):
#         return str(self.start_date.year) + ' Round ' + str(self.season_round)
# 
#     def get_stats(self):
#         """
#         Generates the season stats
#         """
#         player_count = 0
#         results_count = 0
#         total_games_count = 0.0
#         for ladder in self.ladder_set.all():
#             player_count += ladder.league_set.count()
#             results_count += ladder.result_set.count() / 2
#             total_games_count += (ladder.league_set.count() * (ladder.league_set.count() - 1)) / 2
# 
#         percentage_played = (results_count / total_games_count) * 100
# 
#         return {
#             'divisions': self.ladder_set.count(),
#             'percentage_played': "{0:.2f}".format(percentage_played),
#             'total_games_count': total_games_count,
#             'results_count': results_count,
#             'player_count': player_count
#         }
# 
#     def get_leader_stats(self, user):
#         """
#         Generates the list of leaders for current season
#         """
#         current_leaders = {}
# 
#         for ladder in self.ladder_set.all():
#             current_leaders[ladder.id] = ladder.get_leader(user=user)
# 
#         return {
#             'current_leaders': current_leaders,
#         }
# 
#     def get_progress(self):
#         """
#         Query how many games have been played so far.
#         """
#         results = Result.objects.raw("""
#             SELECT ladder_result.id, ladder_id, season_id, date_added, COUNT(*) AS added_count
#             FROM ladder_result LEFT JOIN ladder_ladder
#             ON ladder_result.ladder_id=ladder_ladder.id
#             WHERE season_id = %s GROUP BY DATE(date_added)
#             ORDER BY DATE(date_added) ASC;
#         """, [self.id])
# 
#         leagues = League.objects.raw("""
#             SELECT ladder_league.id, COUNT(*) AS player_count
#             FROM ladder_league LEFT JOIN ladder_ladder
#             ON ladder_league.ladder_id=ladder_ladder.id
#             WHERE season_id = %s GROUP BY ladder_id;
#         """, [self.id])
# 
#         played = []
#         played_days = []
#         played_cumulative = []
#         played_cumulative_count = 0
#         latest_result = False
# 
#         for result in results:
#             played.append(result.added_count)
#             played_days.append((result.date_added - self.start_date).days)
# 
#             played_cumulative_count += result.added_count / 2
#             played_cumulative.append(played_cumulative_count)
#             latest_result = result.date_added
# 
#         total_matches = 0
#         for league in leagues:
#             total_matches += (league.player_count-1) * league.player_count / 2
# 
#         return {
#             "season_days": [0, (self.end_date - self.start_date).days],
#             "season_total_matches": [0, total_matches],
#             "played_days": played_days,
#             "played": played,
#             "played_cumulative": played_cumulative,
#             "latest_result": latest_result.strftime("%B %d, %Y") if latest_result else "-"
#         }
# 
# Path: ladder/views.py
# @cache_page(60 * 60, key_prefix='season')  # 1 hour page cache
# def season(request, year, season_round):
#     season_object = get_object_or_404(Season, start_date__year=year, season_round=season_round)
# 
#     ladders = Ladder.objects.filter(season=season_object)
# 
#     results = Result.objects.filter(ladder__season=season_object)
#     league = League.objects.filter(ladder__season=season_object)
# 
#     results_dict = {}
# 
#     for result in results:
#         results_dict.setdefault(result.player.id, []).append(result)
# 
#     return render(
#         request, 'ladder/season/index.html',
#         dict(season=season_object, ladders=ladders, results_dict=results_dict, league=league)
#     )


# Path: ladder/management/commands/refresh_cache.py
from django.core.management.base import BaseCommand, CommandError
from django.test.client import RequestFactory
from django.conf import settings
from django.urls import reverse
from ladder.models import Season
from ladder.views import season as season_view




class Command(BaseCommand):
    help = 'Refreshes cached pages'

    def handle(self, *args, **options):
        """
        Script that calls all season pages to refresh the cache on them if it has expired.

        Any time/date settings create postfixes on the caching key, for now the solution is to disable them.
        """

        if settings.USE_I18N:
            raise CommandError('USE_I18N in settings must be disabled.')

        if settings.USE_L10N:
            raise CommandError('USE_L10N in settings must be disabled.')

        if settings.USE_TZ:
            raise CommandError('USE_TZ in settings must be disabled.')

        self.factory = RequestFactory()
        seasons = Season.objects.all()
        for season in seasons:
            path = reverse('ladder:season', args=(str(season.end_date.year), str(season.season_round)))
            # use the request factory to generate the correct url for the cache hash
            request = self.factory.get(path)


            season_view(request, season.end_date.year, season.season_round)