# -*- coding: utf-8 -*-

"""
Recalculate Mahjong Rankings...
"""

from datetime import date, datetime, time

from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_date

from mahjong_ranking import models


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

    help = "Recalculate the Kyu/Dan Rankings"

    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.')
        parser.add_argument('-f', '--force', action='store_true',
                            help="Force the recalculation of all Hanchans.")

    def handle(self, *args, **options):
        since = options.get('since', None)
        until = options.get('until', None)
        force_recalc = options.get('force')
        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=force_recalc)
