from django.db import models
from zoneinfo import available_timezones
import uuid
from . import BaseModel

class Club(BaseModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
    creator = models.ForeignKey('CustomUser', blank=True, null=True, on_delete=models.SET_NULL, related_name='creator_clubs')
    name = models.CharField(max_length=50)
    acronym = models.CharField(max_length=50)
    phone = models.CharField(max_length=15, null=True, blank=True)
    code = models.CharField(max_length=10, null=True, blank=True)
    federal_club_data = models.JSONField(null=True, blank=True)

    address = models.CharField(max_length=200, null=True, blank=True)
    city = models.CharField(max_length=100, null=True, blank=True)
    zip_code = models.CharField(max_length=10, null=True, blank=True)
    latitude = models.FloatField(null=True, blank=True)
    longitude = models.FloatField(null=True, blank=True)
    timezone = models.CharField(
        max_length=50, null=True, blank=True,
        choices=[(tz, tz) for tz in sorted(available_timezones())],
        default='CET'
    )
    court_count = models.IntegerField(default=2)
    broadcast_code = models.CharField(max_length=10, null=True, blank=True, unique=True)

    def delete_dependencies(self):
        for court in self.courts.all():
            # court.delete_dependencies()
            court.delete()

    def __str__(self):
        return self.name

    def events_count(self):
        return self.events.count()

    def court_name(self, index):
        for court in self.courts.all():
            if court.index == index and court.name is not None and len(court.name) > 0:
                return court.name

        if index is not None:
            return f"Terrain {index + 1}"

        return ""

    def has_address(self):
        return self.address and self.zip_code and self.city

    def city_zipcode(self):
        if self.has_address():
            return f"{self.zip_code} {self.city}"
        else:
            return ""

    def computedShortTitle(self):
        if len(self.name) > 15:
            return self.acronym
        else:
            return self.name
