"""
Gestion en ligne de commande des mails de rappel.
"""

from datetime import timedelta

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

from bda.models import Spectacle


class Command(BaseCommand):
    help = (
        "Envoie les mails de rappel des spectacles dont la date approche.\n"
        "Ne renvoie pas les mails déjà envoyés."
    )
    leave_locale_alone = True

    def handle(self, *args, **options):
        now = timezone.now()
        delay = timedelta(days=4)
        shows = (
            Spectacle.objects.filter(date__range=(now, now + delay))
            .filter(tirage__active=True)
            .filter(rappel_sent__isnull=True)
            .all()
        )
        for show in shows:
            show.send_rappel()
            self.stdout.write("Mails de rappels pour %s envoyés avec succès." % show)
        if not shows:
            self.stdout.write("Aucun mail à envoyer.")