from django.db import models
from django.apps import apps
from django.contrib.auth.models import AbstractUser
from django.utils.timezone import now

from . import club, enums
import uuid

class CustomUser(AbstractUser):
    pass
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
    last_update = models.DateTimeField(default=now)
    email = models.EmailField(unique=True)
    umpire_code = models.CharField(max_length=50, blank=True, null=True)
    clubs = models.ManyToManyField(club.Club, blank=True, related_name='creators')
    phone = models.CharField(max_length=15, null=True, blank=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    licence_id = models.CharField(max_length=10, unique=True, null=True, blank=True)
    country = models.CharField(max_length=40, null=True, blank=True)

    summons_message_body = models.TextField(blank=True, null=True)
    summons_message_signature = models.TextField(blank=True, null=True)
    summons_available_payment_methods = models.TextField(blank=True, null=True)

    summons_display_format = models.BooleanField(default=False)
    summons_display_entry_fee = models.BooleanField(default=False)
    summons_use_full_custom_message = models.BooleanField(default=False)

    match_formats_default_duration = models.JSONField(blank=True, null=True)

    bracket_match_format_preference = models.IntegerField(default=enums.FederalMatchCategory.NINE_GAMES, choices=enums.FederalMatchCategory.choices, null=True, blank=True)
    group_stage_match_format_preference = models.IntegerField(default=enums.FederalMatchCategory.NINE_GAMES, choices=enums.FederalMatchCategory.choices, null=True, blank=True)
    loser_bracket_match_format_preference = models.IntegerField(default=enums.FederalMatchCategory.NINE_GAMES, choices=enums.FederalMatchCategory.choices, null=True, blank=True)

    device_id = models.CharField(max_length=50, null=True, blank=True)
    agents = models.ManyToManyField('CustomUser', blank=True, related_name='owners')
    loser_bracket_mode = models.IntegerField(default=0)

    origin = models.IntegerField(default=enums.UserOrigin.ADMIN, choices=enums.UserOrigin.choices, null=True, blank=True)
    should_synchronize = models.BooleanField(default=False)

    ### ### ### ### ### ### ### ### ### ### ### WARNING ### ### ### ### ### ### ### ### ### ###
    ### WARNING : Any added field MUST be inserted in the method below: fields_for_update() ###
    ### ### ### ### ### ### ### ### ### ### ### WARNING ### ### ### ### ### ### ### ### ### ###

    def fields_for_update():
        # returns the list of fields to update without password
        return ['id', 'last_update', 'username', 'email', 'umpire_code', 'clubs', 'phone', 'first_name', 'last_name',
            'licence_id', 'country',
            'summons_message_body', 'summons_message_signature', 'summons_available_payment_methods',
            'summons_display_format', 'summons_display_entry_fee',
            'summons_use_full_custom_message', 'match_formats_default_duration', 'bracket_match_format_preference',
            'group_stage_match_format_preference', 'loser_bracket_match_format_preference', 'device_id', 'loser_bracket_mode', 'origin', 'agents', 'should_synchronize']

    def __str__(self):
        return self.username

    def discord_string(self):
        return f"{self.username} : {self.first_name} {self.last_name} | {self.email} | {self.phone}"

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

    def full_name(self):
        return f"{self.first_name} {self.last_name}"

    def latest_event_club_name(self):
        latest_event = self.events.order_by('-creation_date').first()
        if latest_event and latest_event.club:
            return latest_event.club.name
        if self.licence_id:
            PlayerRegistration = apps.get_model('tournaments', 'PlayerRegistration')
            player_registration = PlayerRegistration.objects.filter(licence_id=self.licence_id).order_by('team_registration__registration_date').first()
            try:
                return player_registration.team_registration.tournament.event.club.name
            except AttributeError:
                return None

        return None
