"""
Gestion en ligne de commande des reventes.
"""

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

from bda.models import SpectacleRevente


class Command(BaseCommand):
    help = (
        "Envoie les mails de notification et effectue les tirages au sort des reventes"
    )
    leave_locale_alone = True

    def handle(self, *args, **options):
        now = timezone.now()
        reventes = SpectacleRevente.objects.all()
        for revente in reventes:
            # Le spectacle est bientôt et on a pas encore envoyé de mail :
            # on met la place au shotgun et on prévient.
            if revente.is_urgent and not revente.notif_sent:
                if revente.can_notif:
                    self.stdout.write(str(now))
                    revente.mail_shotgun()
                    self.stdout.write(
                        "Mails de disponibilité immédiate envoyés "
                        "pour la revente [%s]" % revente
                    )

            # Le spectacle est dans plus longtemps : on prévient
            elif revente.can_notif and not revente.notif_sent:
                self.stdout.write(str(now))
                revente.send_notif()
                self.stdout.write(
                    "Mails d'inscription à la revente [%s] envoyés" % revente
                )

            # On fait le tirage
            elif now >= revente.date_tirage and not revente.tirage_done:
                self.stdout.write(str(now))
                winner = revente.tirage()
                self.stdout.write("Tirage effectué pour la revente [%s]" % revente)

                if winner:
                    self.stdout.write("Gagnant : %s" % winner.user)
                else:
                    self.stdout.write("Pas de gagnant ; place au shotgun")