# 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 "-"
#         }
# 
# class LadderSubscription(models.Model):
#     ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE)
#     user = models.ForeignKey(User, on_delete=models.CASCADE)
#     subscribed_at = models.DateField()
# 
#     def __str__(self):
#         return self.user.email
# 
# Path: tennis/settings.py
# SUBSCRIPTION_EMAIL = os.environ.get('SUBSCRIPTION_EMAIL')


import datetime
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from django.template.loader import get_template
from ladder.models import Season, LadderSubscription
from tennis.settings import SUBSCRIPTION_EMAIL
    # search current season ladders that have result in last 24 hours
    season = Season.objects.latest('start_date')
    print(season)
    ladders = season.ladder_set.all()

    # iterate through subscriptions and send email
    for ladder in ladders:
        print(ladder)

        # check ladder has results
        date_from = datetime.datetime.now() - datetime.timedelta(days=1)
        if ladder.result_set.filter(date_added__gte=date_from).count() == 0:
            print('No results in past day')
            continue

        subscriptions = ladder.laddersubscription_set.all()
        for subscription in subscriptions:
            print(subscription)

            # using https://github.com/leemunroe/responsive-html-email-template
            message = get_template("ladder/ladder/subscription/email.html").render({
                'ladder': ladder,
                'user': subscription.user,
                'protocol': 'https',
                'domain': 'highgate-ladder.co.uk' # todo: use use site framework to do these
            })

            mail = EmailMessage(
                subject=ladder.__str__() + " Result Update",
                body=message,

# 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 "-"
#         }
# 
# class LadderSubscription(models.Model):
#     ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE)
#     user = models.ForeignKey(User, on_delete=models.CASCADE)
#     subscribed_at = models.DateField()
# 
#     def __str__(self):
#         return self.user.email
# 
# Path: tennis/settings.py
# SUBSCRIPTION_EMAIL = os.environ.get('SUBSCRIPTION_EMAIL')


# Path: ladder/management/commands/subscription_email.py
import datetime
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from django.template.loader import get_template
from ladder.models import Season, LadderSubscription
from tennis.settings import SUBSCRIPTION_EMAIL

    # search current season ladders that have result in last 24 hours
    season = Season.objects.latest('start_date')
    print(season)
    ladders = season.ladder_set.all()

    # iterate through subscriptions and send email
    for ladder in ladders:
        print(ladder)

        # check ladder has results
        date_from = datetime.datetime.now() - datetime.timedelta(days=1)
        if ladder.result_set.filter(date_added__gte=date_from).count() == 0:
            print('No results in past day')
            continue

        subscriptions = ladder.laddersubscription_set.all()
        for subscription in subscriptions:
            print(subscription)

            # using https://github.com/leemunroe/responsive-html-email-template
            message = get_template("ladder/ladder/subscription/email.html").render({
                'ladder': ladder,
                'user': subscription.user,
                'protocol': 'https',
                'domain': 'highgate-ladder.co.uk' # todo: use use site framework to do these
            })

            mail = EmailMessage(
                subject=ladder.__str__() + " Result Update",
                body=message,

                from_email=SUBSCRIPTION_EMAIL,