# Copyright (C) 2020 by Animath
# SPDX-License-Identifier: GPL-3.0-or-later

from django.core.management import BaseCommand
from django.db.models import Q
from participation.models import Team, Tournament
from registration.models import ParticipantRegistration, VolunteerRegistration
from tfjm.lists import get_sympa_client


class Command(BaseCommand):
    def handle(self, *args, **options):
        """
        Create Sympa mailing lists and register teams.
        """
        sympa = get_sympa_client()

        sympa.create_list("equipes", "Equipes du TFJM2", "hotline",
                          "Liste de diffusion pour contacter toutes les equipes validees du TFJM2.",
                          "education", raise_error=False)
        sympa.create_list("equipes-non-valides", "Equipes non valides du TFJM2", "hotline",
                          "Liste de diffusion pour contacter toutes les equipes non validees du TFJM2.",
                          "education", raise_error=False)

        sympa.create_list("admins", "Administrateur⋅rices du TFJM2", "hotline",
                          "Liste de diffusion pour contacter toustes les administrateur.rices du TFJM2.",
                          "education", raise_error=False)
        sympa.create_list("organisateurs", "Organisateurs du TFJM2", "hotline",
                          "Liste de diffusion pour contacter toustes les organisateur.rices du TFJM2.",
                          "education", raise_error=False)
        sympa.create_list("jurys", "Jurys du TFJM2", "hotline",
                          "Liste de diffusion pour contacter tous les jurys du TFJM2.",
                          "education", raise_error=False)

        for tournament in Tournament.objects.all():
            slug = tournament.name.lower().replace(" ", "-")
            sympa.create_list(f"equipes-{slug}", f"Equipes du tournoi {tournament.name}", "hotline",
                              f"Liste de diffusion pour contacter toutes les equipes du tournoi {tournament.name}"
                              " du TFJM2.", "education", raise_error=False)
            sympa.create_list(f"organisateurs-{slug}", f"Organisateurs du tournoi {tournament.name}", "hotline",
                              "Liste de diffusion pour contacter tous les organisateurs du tournoi "
                              f"{tournament.name} du TFJM2.", "education", raise_error=False)
            sympa.create_list(f"jurys-{slug}", f"Jurys du tournoi {tournament.name}", "hotline",
                              f"Liste de diffusion pour contacter tous les jurys du tournoi {tournament.name}"
                              f" du TFJM2.", "education", raise_error=False)

            sympa.subscribe(tournament.teams_email, "equipes", True)
            sympa.subscribe(tournament.organizers_email, "organisateurs", True)
            sympa.subscribe(tournament.jurys_email, "jurys", True)

        for team in Team.objects.filter(participation__valid=True).all():
            team.create_mailing_list()
            sympa.unsubscribe(team.email, "equipes-non-valides", True)
            sympa.subscribe(team.email, f"equipes-{team.participation.tournament.name.lower().replace(' ', '-')}",
                            True, f"Equipe {team.name}")

        for team in Team.objects.filter(Q(participation__valid=False) | Q(participation__valid__isnull=True)).all():
            team.create_mailing_list()
            sympa.subscribe(team.email, "equipes-non-valides", True, f"Equipe {team.name}")

        for participant in ParticipantRegistration.objects.filter(team__isnull=False).all():
            sympa.subscribe(participant.user.email, f"equipe-{participant.team.trigram.lower()}",
                            True, f"{participant}")

        for volunteer in VolunteerRegistration.objects.all():
            for organized_tournament in volunteer.organized_tournaments.all():
                slug = organized_tournament.name.lower().replace(" ", "-")
                sympa.subscribe(volunteer.user.email, f"organisateurs-{slug}", True)

            for jury_in in volunteer.jury_in.all():
                slug = jury_in.tournament.name.lower().replace(" ", "-")
                sympa.subscribe(volunteer.user.email, f"jurys-{slug}", True)

        for admin in VolunteerRegistration.objects.filter(admin=True).all():
            sympa.subscribe(admin.user.email, "admins", True)
