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

from pathlib import Path

from django.core.management import BaseCommand
from participation.models import Team


class Command(BaseCommand):
    help = """Cette commande permet d'exporter dans le dossier output/photo_authorizations l'ensemble des
    autorisations de droit à l'image des participant⋅es, triées par équipe, incluant aussi celles de la finale."""

    def handle(self, *args, **kwargs):
        base_dir = Path(__file__).parent.parent.parent.parent
        base_dir /= "output"
        if not base_dir.is_dir():
            base_dir.mkdir()
        base_dir /= "photo_authorizations"
        if not base_dir.is_dir():
            base_dir.mkdir()

        for team in Team.objects.filter(participation__valid=True).all():
            team_dir = base_dir / f"{team.trigram} - {team.name}"
            if not team_dir.is_dir():
                team_dir.mkdir()

            for participant in team.participants.all():
                if participant.photo_authorization:
                    with participant.photo_authorization.file as file_input:
                        with open(team_dir / f"{participant}.pdf", 'wb') as file_output:
                            file_output.write(file_input.read())

                if participant.photo_authorization_final:
                    with participant.photo_authorization_final.file as file_input:
                        with open(team_dir / f"{participant} (finale).pdf", 'wb') as file_output:
                            file_output.write(file_input.read())
