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

from pathlib import Path

from django.conf import settings
from django.core.management import BaseCommand
from django.utils.translation import activate
from participation.models import Solution, Tournament


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        activate('fr')

        base_dir = Path(__file__).parent.parent.parent.parent
        base_dir /= "output"
        if not base_dir.is_dir():
            base_dir.mkdir()
        base_dir /= "Par équipe"
        if not base_dir.is_dir():
            base_dir.mkdir()

        tournaments = Tournament.objects.all()
        for tournament in tournaments:
            self.handle_tournament(tournament, base_dir)

        base_dir = base_dir.parent / "Par problème"
        if not base_dir.is_dir():
            base_dir.mkdir()

        for problem_id, problem_name in enumerate(settings.PROBLEMS):
            dir_name = f"Problème n°{problem_id + 1} : {problem_name}"
            problem_dir = base_dir / dir_name
            if not problem_dir.is_dir():
                problem_dir.mkdir()
            self.handle_problem(problem_id + 1, problem_dir)

    def handle_tournament(self, tournament, base_dir):
        name = tournament.name
        tournament_dir = base_dir / name
        if not tournament_dir.is_dir():
            tournament_dir.mkdir()

        for participation in tournament.participations.filter(valid=True).all():
            self.handle_participation(participation, tournament_dir)

    def handle_participation(self, participation, tournament_dir):
        name = participation.team.name
        trigram = participation.team.trigram
        team_dir = tournament_dir / f"{name} ({trigram})"
        if not team_dir.is_dir():
            team_dir.mkdir()

        for solution in participation.solutions.all():
            filename = f"{solution}.pdf"
            with solution.file as file_input:
                with open(team_dir / filename, 'wb') as file_output:
                    file_output.write(file_input.read())

    def handle_problem(self, problem_id, directory):
        solutions = Solution.objects.filter(problem=problem_id).all()

        for solution in solutions:
            team = solution.participation.team
            tournament_name = team.participation.tournament.name
            output_file = directory / f'{solution}.pdf'
            if output_file.is_file():
                output_file.unlink()
            output_file.symlink_to(f'../../Par équipe/{tournament_name}/{team.name} ({team.trigram})/{solution}.pdf')
