from django.db import models
from . import Tournament, FederalMatchCategory
import uuid

class Round(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
    tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)
    index = models.IntegerField(default=0)
    parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children')
    format = models.IntegerField(default=FederalMatchCategory.NINE_GAMES, choices=FederalMatchCategory.choices, null=True, blank=True)
    start_date = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        if self.parent:
            return f"LB: {self.name()}"
        else:
            return self.name()
        # if self.parent:
        #     return f"{self.tournament.display_name()} - LB: {self.name()}"
        # else:
        #     return f"{self.tournament.display_name()} - {self.name()}"

    def name(self):
        if self.parent:
            return "Matchs de classement"
        else:
            if self.index == 0:
                return "Finale"
            elif self.index == 1:
                return "Demi-Finales"
            elif self.index == 2:
                return "Quarts de finale"
            else:
                squared = 2 ** self.index
                return f"{squared}ème"

    def ranking_matches(self, hide_empty_matches):
        matches = []
        for child in self.children.all():

            child_matches = child.match_set.all()
            if hide_empty_matches:
                child_matches = [m for m in child_matches if m.should_appear()]
            else:
                child_matches = [m for m in child_matches if m.disabled is False]

            matches.extend(child_matches)
            matches.extend(child.ranking_matches(hide_empty_matches))
        return matches

    def all_matches(self, hide_empty_matches):
        matches = []
        matches.extend(self.get_matches_recursive(hide_empty_matches))
        return matches

    def get_matches_recursive(self, hide_empty_matches):
        matches = list(self.match_set.all())  # Retrieve matches associated with the current round
        matches = [m for m in matches if m.should_appear()]
        if hide_empty_matches:
            matches = [m for m in matches if m.should_appear()]
        else:
            matches = [m for m in matches if m.disabled is False]

        matches.sort(key=lambda m: m.index)

        # Recursively fetch matches from child rounds
        for child_round in self.children.all():
            matches.extend(child_round.get_matches_recursive(hide_empty_matches))

        return matches

    def root_round(self):
        if self.parent is None:
            return self
        else:
            return self.parent.root_round()
