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

class Round(SideStoreModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
    tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, related_name='rounds', null=True)
    index = models.IntegerField(default=0)
    parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, 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)
    group_stage_loser_bracket = models.BooleanField(default=False)
    loser_bracket_mode = models.IntegerField(default=0)

    def delete_dependencies(self):
        for round in self.children.all():
            round.delete_dependencies()
            round.delete()
        for match in self.matches.all():
            match.delete_dependencies()
            match.delete()

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

    def save(self, *args, **kwargs):
        self.store_id = str(self.get_tournament_id())
        super().save(*args, **kwargs)

    def get_tournament_id(self):
        return self.tournament.id

    def name(self):
        if self.parent:
            return "Matchs de classement"
        elif self.group_stage_loser_bracket is True:
            return "Matchs de classement de poule"
        else:
            if self.index == 0:
                return "Finale"
            elif self.index == 1:
                return "Demi"
            elif self.index == 2:
                return "Quart"
            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.matches.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.matches.all())  # Retrieve matches associated with the current round
        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 get_depth(self):
        depth = 0
        current_round = self
        while current_round.parent:
            depth += 1
            current_round = current_round.parent
        return depth

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

    def all_matches_are_over(self):
        for match in self.matches.all():
            if match.end_date is None and match.disabled is False:
                return False

        return True
