from django.db import models
from . import BaseModel, Club, CustomUser
import uuid

class Event(BaseModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
    club = models.ForeignKey(Club, on_delete=models.SET_NULL, null=True, blank=True, related_name='events')
    creation_date = models.DateTimeField()
    creator = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL, related_name='events')
    name = models.CharField(max_length=200, null=True, blank=True)
    federal_tournament_data = models.JSONField(null=True, blank=True)
    tenup_id = models.CharField(max_length=20, null=True, blank=True)
    creator_full_name = models.CharField(max_length=200, null=True, blank=True)

    def delete_dependencies(self):
        for tournament in self.tournaments.all():
            tournament.delete_dependencies()
            tournament.delete()
        for date_interval in self.date_intervals.all():
            date_interval.delete_dependencies()
            date_interval.delete()

    def __str__(self):
        return self.display_name()

    def save(self, *args, **kwargs):
        if self.creator:
            self.creator_full_name = self.creator.full_name()
        super(Event, self).save(*args, **kwargs)

    def display_name(self):
        if self.club and self.club.name and self.name:
            return self.club.computedShortTitle() + " " + self.name
        if self.name:
            return self.name
        elif self.club and self.club.name:
            return self.club.name
        else:
            return self.creation_date.strftime("%Y-%m-%d %H:%M")

    def display_long_name(self):
        if self.club and self.club.name and self.name:
            return self.club.name + " " + self.name
        if self.name:
            return self.name
        elif self.club and self.club.name:
            return self.club.name
        else:
            return self.creation_date.strftime("%Y-%m-%d %H:%M")
