from django.db import models
from django.utils import timezone
from django.db.models.signals import post_delete
from django.utils.timezone import localtime

import locale    

class Club(models.Model):
    name = models.CharField(max_length=200)
    header = models.CharField(max_length=200, blank=True)
    footer = models.CharField(max_length=200, blank=True)

    def __str__(self):
        return self.name

class Tournament(models.Model):
    club = models.ForeignKey(Club, on_delete=models.CASCADE, default=None)
    name = models.CharField(max_length=200)
    auto_scrolling = models.BooleanField(default=False)
    shortname = models.CharField(max_length=200, blank=True)
    tournament_index = models.IntegerField(default=0)

    def __str__(self):
        return self.name

    def brackets(self):
        return self.matches.filter(isBracket=True).order_by('court')

    def live_matches(self):
        return self.matches.filter(enddate__isnull=True).order_by('court')

    def ended_matches(self):
        return self.matches.filter(enddate__isnull=False).order_by('court')
        
    def teams(self):
        return self.team_set.order_by('position')
    def teamsByFinalRank(self):
        return self.team_set.order_by('position_finale').filter(position_finale__gt=0)

class Team(models.Model):
    name = models.CharField(max_length=200, blank=True)
    rank = models.IntegerField(default=0)
    position = models.IntegerField(default=0)
    position_finale = models.IntegerField(default=0)
    bracket = models.BooleanField(default=False)
    position_label = models.CharField(max_length=200, blank=True)
    date_label = models.CharField(max_length=200, blank=True)
    background_color = models.CharField(max_length=200, blank=True)
    position_finale = models.IntegerField(default=0)
    couleur_finale = models.CharField(max_length=200, blank=True)
    points_label = models.CharField(max_length=200, blank=True)

    tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, default=None, blank=True, null=True)
    def players(self):
        return self.player_set.order_by('rank')



class Player(models.Model):
    name = models.CharField(max_length=200, blank=True)
    rank = models.IntegerField(default=0)
    club_name = models.CharField(max_length=200, blank=True)
    ligue_name = models.CharField(max_length=200, blank=True)
    team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None, blank=True, null=True)
    
class Match(models.Model):
    tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, default=None)
    date = models.DateTimeField('start date')
    enddate = models.DateTimeField('end date', null=True, blank=True)
    court = models.IntegerField(default=0)
    match_index = models.IntegerField(default=0)
    refreshrate = models.IntegerField(default=10)
    hasWalkOutTeam = models.BooleanField(default=False)

    title = models.CharField(max_length=200, blank=True)
    team1 = models.CharField(max_length=200, blank=True)
    team2 = models.CharField(max_length=200, blank=True)
    team3 = models.CharField(max_length=200, blank=True)
    team4 = models.CharField(max_length=200, blank=True)
    team5 = models.CharField(max_length=200, blank=True)

    team1scorecolumn1 = models.CharField(max_length=200, blank=True)
    team1scorecolumn2 = models.CharField(max_length=200, blank=True)
    team1scorecolumn3 = models.CharField(max_length=200, blank=True)
    team1scorecolumn4 = models.CharField(max_length=200, blank=True)
    team1scorecolumn5 = models.CharField(max_length=200, blank=True)
    team2scorecolumn1 = models.CharField(max_length=200, blank=True)
    team2scorecolumn2 = models.CharField(max_length=200, blank=True)
    team2scorecolumn3 = models.CharField(max_length=200, blank=True)
    team2scorecolumn4 = models.CharField(max_length=200, blank=True)
    team2scorecolumn5 = models.CharField(max_length=200, blank=True)

    teamOne = models.ForeignKey(Team, related_name="teamOne", on_delete=models.SET_NULL, default=None, blank=True, null=True)
    teamTwo = models.ForeignKey(Team, related_name="teamTwo", on_delete=models.SET_NULL, default=None, blank=True, null=True)
    
    def poule(self):
        return self.court / 100

    def isMatch(self):
        if self.court < 100 and self.court >= 0:
            return True
        else :
            return False

    def isBracket(self):
        if self.court >= 100 and self.court < 1000:
            return True
        else :
            return False

    def isStatistic(self):
        if self.court >= 1000:
            return True
        else :
            return False

    def hasEnded(self):
        if self.enddate:
            return True
        else:
            return False

    def durationPrefix(self):

        _seconds = 0
        if self.enddate:
            _seconds = (self.enddate - self.date).total_seconds()
        else:
            _seconds = (timezone.now() - self.date).total_seconds()

        if _seconds > 0:
            return "Temps de jeu"
        else :
            _hours = int(_seconds / 3600)
            if _hours < -1 and self.hasEnded():
                return "Démarrage prévu"
            else :
                return "Démarrage prévu dans"

    def duration(self):
        locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
        _seconds = 0
        if self.enddate:
            _seconds = (self.enddate - self.date).total_seconds()
        else:
            _seconds = (timezone.now() - self.date).total_seconds()

        if _seconds > 0:
                _hours = int(_seconds / 3600)
                _minutes = int((_seconds % 3600) / 60)
                return f"{_hours:02d}h{_minutes:02d}min"
        else :
            _hours = int(_seconds / 3600)
            if _hours < -1 and self.hasEnded() == False:
                return localtime(self.date).strftime("%A %d %B à %H:%M")
            else :
                _seconds = _seconds * -1
                _hours = _hours * -1
                _minutes = int((_seconds % 3600) / 60)
                return f"{_hours:02d}h{_minutes:02d}min"


    def seconds(self):
        return (timezone.now() - self.date).total_seconds()

def delete_reverse(sender, **kwargs):
    try:
        if not kwargs['instance'].teamOne.tournament:        
            kwargs['instance'].teamOne.delete()
        if not kwargs['instance'].teamTwo.tournament:        
            kwargs['instance'].teamTwo.delete()
    except:
        pass

post_delete.connect(delete_reverse, sender=Match)
