"""
Recalculates all Kyu/Dan Rankings until the given date a writes them to the legacy fields.
"""

from django.core.management.base import BaseCommand
from datetime import datetime, date, time
from mahjong_ranking import models
from django.utils.dateparse import parse_date
from django.utils import timezone

LEGACY_ATTRIBUTES = (
    "dan",
    "dan_points",
    "max_dan_points",
    "kyu",
    "kyu_points",
    "hanchan_count",
    "good_hanchans",
    "won_hanchans"
)


class Command(BaseCommand):
    """ Recalculates all Kyu/Dan Rankings until the given date a writes them to the legacy fields. """

    help = "Recalculates all Kyu/Dan Rankings until the given date a writes them to the legacy fields."

    def add_arguments(self, parser):
        parser.add_argument('-s', '--since', nargs='?', type=parse_date,
                            metavar='YYYY-MM-DD',
                            help='Use all Hanchans since the given date.')
        parser.add_argument('-u', '--until', nargs='?', type=parse_date,
                            metavar='YYYY-MM-DD',
                            help='Only use Hanchans until the given date.')

    def handle(self, *args, **options):
        since = options.get('since', None)
        until = options.get('until', None)
        if isinstance(since, date):
            since = datetime.combine(since, time(0, 0, 0))
            since = timezone.make_aware(since)
        if isinstance(until, date):
            until = datetime.combine(until, time(23, 59, 59))
            until = timezone.make_aware(until)
        models.KyuDanRanking.objects.update(since=since, until=until, force_recalc=True)
        # write the updated values to the legacy fields
        for ranking in models.KyuDanRanking.objects.all():
            print(ranking)
            for attribute in LEGACY_ATTRIBUTES:
                setattr(ranking, f"legacy_{attribute}", getattr(ranking, attribute))
                value = getattr(ranking, attribute)
                legacy_value = getattr(ranking, f"legacy_{attribute}")
                print(f"{attribute}: {value}, legacy_{attribute}: {legacy_value}")
            ranking.legacy_date = until.date()
            print(f"legacy_date: {ranking.legacy_date}")
            ranking.save()
