"""Export Mahjong Rankings as excel files."""

import os
from datetime import date, time, datetime

from django.conf import settings
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_date

from kasu import xlsx
from mahjong_ranking.models import SeasonRanking, KyuDanRanking

MAIL_BODY = """
Hallo! Ich bin's dein Server.
 
Ich habe gerade die Mahjong Rankings als Excel exportiert und dachte mir das
ich sie dir am besten gleich schicke.

Bitte versuche nicht auf diese E-Mail zu antworten. 
Ich bin nur ein dummes Programm.

mit lieben Grüßen

Der Kasu Server
"""


def export_season_rankings(workbook, until):
    SeasonRanking.objects.update(until=until)
    season = until.year if until else date.today().year
    object_list = SeasonRanking.objects.season_rankings()
    title = "Mahjong Ladder - {}".format(season)
    columns_settings = (
        {'col': 'A', 'title': 'Rang', 'attr': 'placement', 'style': 'Integer',
         'width': 8},
        {'col': 'B', 'title': 'Spitzname', 'attr': 'user.username',
         'style': 'Content',
         'width': 25},
        {'col': 'C', 'title': '⌀ Platz', 'attr': 'avg_placement',
         'style': 'Float', 'width': 8},
        {'col': 'D', 'title': '⌀ Punkte', 'attr': 'avg_score',
         'style': 'Float', 'width': 12},
        {'col': 'E', 'title': 'Hanchans', 'attr': 'hanchan_count',
         'style': 'Integer', 'width': 10},
        {'col': 'F', 'title': 'Gut', 'attr': 'good_hanchans',
         'style': 'Integer', 'width': 5},
        {'col': 'G', 'title': 'Gewonnen', 'attr': 'won_hanchans',
         'style': 'Integer', 'width': 10},
    )
    workbook.generate_sheet(
        title=title,
        columns_settings=columns_settings,
        object_list=object_list)


def export_kyu_dan_rankings(workbook, until):
    KyuDanRanking.objects.update(until=until, force_recalc=True)
    object_list = KyuDanRanking.objects.all()
    title = "Kyū & Dan Rankings"
    columns_settings = (
        {'col': 'A', 'title': 'Spitzname', 'attr': 'user.username',
         'style': 'Content', 'width': 14},
        {'col': 'B', 'title': 'Voller Name', 'attr': 'user.full_name',
         'style': 'Content', 'width': 20},
        {'col': 'C', 'title': 'Rang', 'attr': 'rank',
         'style': 'Content', 'width': 8},
        {'col': 'D', 'title': 'Punkte', 'attr': 'points',
         'style': 'Integer', 'width': 8},
        {'col': 'E', 'title': 'Hanchans', 'attr': 'hanchan_count',
         'style': 'Integer', 'width': 10},
        {'col': 'F', 'title': 'Gut', 'attr': 'good_hanchans',
         'style': 'Integer', 'width': 5},
        {'col': 'G', 'title': 'Gewonnen', 'attr': 'won_hanchans',
         'style': 'Integer', 'width': 10},
        {'col': 'H', 'title': 'letzte Hanchan', 'attr': 'last_hanchan_date',
         'style': 'Date', 'width': 16},
    )
    workbook.generate_sheet(
        title=title,
        columns_settings=columns_settings,
        object_list=object_list)


class Command(BaseCommand):
    """Exports the SeasonRankings"""
    filename = str()
    until = datetime

    def add_arguments(self, parser):
        parser.add_argument(
            '--until', nargs='?', type=parse_date,
            default=date.today(), metavar='YYYY-MM-DD',
            help='Calculate and export rankings until the given date.')
        parser.add_argument(
            '--mail', nargs='*', type=str, metavar='user@example.com',
            help='Send the spreadsheet via eMail to the given recipient.')

    def handle(self, *args, **options):
        """Exports the current ladder ranking in a spreadsheet.
        This is useful as a backup in form of a hardcopy."""
        self.until = timezone.make_aware(datetime.combine(
            options['until'], time(23, 59, 59)
        ))

        self.filename = os.path.join(
            settings.RANKING_EXPORT_PATH,
            'mahjong_rankings_{:%Y-%m-%d}.xlsx'.format(self.until)
        )
        workbook = xlsx.Workbook()
        export_season_rankings(workbook, until=self.until)
        export_kyu_dan_rankings(workbook, until=self.until)
        os.makedirs(settings.RANKING_EXPORT_PATH, exist_ok=True)
        workbook.save(self.filename)
        if options['mail']:
            self.send_mail(options['mail'])

    def send_mail(self, recipients):
        mail = EmailMessage(
            subject='Mahjong Rankings vom {:%d.%m.%Y}'.format(self.until),
            body=MAIL_BODY,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=recipients)
        mail.attach_file(self.filename)
        mail.send()
