"""
Rest all dan points to 0 at a given date.
"""

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

class Command(BaseCommand):
    """ Recalculate all Kyu/Dan Rankings """

    help = "reset every dan player to 1st dan with 0 points."

    def add_arguments(self, parser):
        parser.add_argument('reset_date', type=parse_date)

    def handle(self, *args, **options):
        legacy_attrs = [ key for key in models.KyuDanRanking.__dict__.keys()
                         if key.startswith('legacy') ]
        legacy_attrs.remove('legacy_date')
        reset_date = timezone.make_aware(datetime.combine(
            options.get('reset_date'), time(23, 59, 59)))
        models.KyuDanRanking.objects.update(until=reset_date, force_recalc=True)
        for ranking in models.KyuDanRanking.objects.filter(dan__gt=0):
            print(ranking)
            ranking.dan = 1
            ranking.dan_points = 0
            ranking.kyu = None
            ranking.kyu_points = 0
            ranking.wins_in_a_row = 0
            ranking.legacy_date = reset_date.date()
            for legacy_attr in legacy_attrs:
                attr = legacy_attr.split("_", maxsplit=1)[1]
                print(ranking, legacy_attr, attr, getattr(ranking, attr))
                setattr(ranking, legacy_attr, getattr(ranking, attr))
            ranking.save()
