from django.contrib import messages
from django.utils import timezone
from ..models import PlayerRegistration, UnregisteredTeam, UnregisteredPlayer
from ..models.player_enums import PlayerDataSource
from ..services.email_service import TournamentEmailService

class TournamentUnregistrationService:
    def __init__(self, request, tournament):
        self.request = request
        self.tournament = tournament
        self.player_registration = None
        self.other_player = None

    def can_unregister(self):
        if not self.tournament.is_unregistration_possible():
            messages.error(self.request, "Le désistement n'est plus possible pour ce tournoi. Si vous souhaitez vous désinscrire, veuillez contacter le juge-arbitre.")
            return False

        if not self.request.user.licence_id:
            messages.error(self.request,
                "Vous ne pouvez pas vous désinscrire car vous n'avez pas de numéro de licence associé.")
            return False

        return True

    def process_unregistration(self):
        if not self._find_player_registration():
            messages.error(self.request,
                "La désincription a échouée. Veuillez contacter le juge-arbitre.")
            return False

        self._unregister_team()
        self._delete_registered_team()
        self._cleanup_session()
        return True

    def _unregister_team(self):
        # Create unregistered team record
        team_registration = self.player_registration.team_registration

        unregistered_team = UnregisteredTeam.objects.create(
            tournament=team_registration.tournament,
            unregistration_date=timezone.now(),
        )

        for player in team_registration.player_registrations.all():
            UnregisteredPlayer.objects.create(
                unregistered_team=unregistered_team,
                first_name=player.first_name,
                last_name=player.last_name,
                licence_id=player.licence_id,
            )

    def _find_player_registration(self):
        self.player_registration = PlayerRegistration.objects.filter(
            licence_id__icontains=self.request.user.licence_id,
            team_registration__tournament_id=self.tournament.id,
        ).first()

        if self.player_registration:
            team_registration = self.player_registration.team_registration
            self.other_player = team_registration.get_other_player(self.player_registration)
            return True
        return False

    def _delete_registered_team(self):
        team_registration = self.player_registration.team_registration
        team_registration.delete()

    def _cleanup_session(self):
        self.request.session['team_registration'] = []
        self.request.session.modified = True
