from rest_framework import serializers

from django.db.models.query import QuerySet

from django.contrib.auth.models import User

from .models import TournamentModel, tournament_manager

from profiles.models import ProfileModel
from profiles.serializers import ProfileSerializer
from games.serializers import GameSerializer

class TournamentSerializer(serializers.ModelSerializer):

    levels = serializers.SerializerMethodField(read_only=True, required=False)
    state = serializers.SerializerMethodField(read_only=True, required=False)
    participants = serializers.SerializerMethodField(read_only=True, required=False)
    level = serializers.ReadOnlyField()
    started = serializers.ReadOnlyField()
    finished = serializers.ReadOnlyField()
    name = serializers.CharField(default="")

    class Meta:
        model = TournamentModel
        fields = ["name", "nb_players", "nb_players_by_game", "level", "started", "finished", "levels", "id", "state", "participants"]

    def get_participants(self, instance: TournamentModel):
        
        participants_id: list[ProfileModel]
        
        if (instance.started):
            participants_id = instance.get_participants_id()
        else:
            participants_id = tournament_manager.get(instance.pk).get_participants_id()

        participants_profile: list[ProfileModel] = []
        for participant_id in participants_id:
            query: QuerySet = ProfileModel.objects.filter(user_id = participant_id)
            profile_data: dict
            if query.exists():
                profile_data = ProfileSerializer(query[0]).data
            else:
                profile_data = { 
                    "username": "deleted_user",
                    "avatar": "/static/avatars/default.avif",
                    "user_id": participants_id
                }
            participants_profile.append(profile_data)
        
        return participants_profile

    def get_state(self, instance: TournamentModel):
        return ["waiting", "started", "finished"][instance.started + instance.finished]

    def get_levels(self, instance: TournamentModel):
        levels: list[list[int]] = []
        for i in range(instance.level):
            games_id: [int] = instance.get_games_id_by_level(i)
            if (games_id == []):
                break
            levels.append(games_id)
        return levels

    def validate_nb_players(self, value: int):
        if (value < 2):
            raise serializers.ValidationError("The numbers of players must be greather than 2.")
        return value
    
    def validate_nb_players_by_game(self, value: int):
        if (value < 2):
            raise serializers.ValidationError("The numbers of players by game must be greather than 2.")
        nb_players: str = self.initial_data.get("nb_players")
        if (nb_players is not None and nb_players.isnumeric()):
            nb_players: int = int(nb_players)
            if (value > nb_players):
                raise serializers.ValidationError("The numbers of players by game must be smaller than the numbers of players.")
        return value