from django.db import models
from django.db.models.sql.query import Q
from . import Tournament, GroupStage, Match
import uuid
from django.utils import timezone

class TeamRegistration(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
    tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)
    group_stage = models.ForeignKey(GroupStage, null=True, blank=True, on_delete=models.SET_NULL)
    registration_date = models.DateTimeField(null=True, blank=True)
    call_date = models.DateTimeField(null=True, blank=True)
    bracket_position = models.IntegerField(null=True, blank=True)
    group_stage_position = models.IntegerField(null=True, blank=True)
    comment = models.CharField(max_length=200, null=True, blank=True)
    source = models.CharField(max_length=20, null=True, blank=True)
    source_value = models.CharField(max_length=200, null=True, blank=True)
    logo = models.CharField(max_length=200, null=True, blank=True) #models.FilePathField(path=os.path.join(settings.STATIC_ROOT, "images"), null=True, blank=True)
    name = models.CharField(max_length=200, null=True, blank=True)

    walk_out = models.BooleanField(default=False)
    wild_card_bracket = models.BooleanField(default=False)
    wild_card_group_stage = models.BooleanField(default=False)
    weight = models.IntegerField(default=0)
    locked_weight = models.IntegerField(null=True, blank=True)

    confirmation_date = models.DateTimeField(null=True, blank=True)
    qualified = models.BooleanField(default=False)

    final_ranking = models.IntegerField(null=True, blank=True)
    points_earned = models.IntegerField(null=True, blank=True)


    def __str__(self):
        if self.name:
            return self.name
            # return f"{self.name}: {self.player_names()}"
        return self.player_names()

    def team_names(self):
        if self.name:
            return [self.name]
        else:
            return [pr.name() for pr in self.playerregistration_set.all()]

    def shortened_team_names(self):
        if self.name:
            return [self.name]
        else:
            return [pr.shortened_name() for pr in self.playerregistration_set.all()]

    def player_names(self):
        names = [pr.name() for pr in self.playerregistration_set.all()]
        str = " - ".join(names)
        if len(str) > 0:
            return str
        else:
            return "no players"

    def next_match(self):
        all_matches = [ts.match for ts in self.teamscore_set.all()]
        now = timezone.now()
        all_matches = sorted(all_matches, key=lambda m: m.start_date if m.start_date is not None else now)
        matches = [m for m in all_matches if m.end_date is None]
        if matches:
            return matches[0]
        else:
            return None

    def next_stage(self):
        matches = map(lambda ts: ts.match, self.teamscore_set.all())
        matches = [m for m in matches if m.group_stage is None]
        matches = sorted(matches, key=lambda m: m.round.index)

        # matches = self.teamscore_set
        # matches = Match.objects.filter(group_stage__isnull=True, team_scores__player_registrations__id=self.id).order_by('round__index')
        # print(f"matches = {len(matches)}")
        if matches:
            return matches[0].round.name()
        elif self.group_stage:
            return self.group_stage.name()
        else:
            return "--"

    def is_valid_for_summon(self):
        return len(self.playerregistration_set.all()) > 0

    def initial_weight(self):
        if self.locked_weight is None:
            return self.weight
        else:
            return self.locked_weight
