from rest_framework import serializers

from django.contrib.auth.models import User
from django.db.models import QuerySet

from .models import GameModel, GameMembersModel

class GameSerializer(serializers.ModelSerializer):

    players = serializers.SerializerMethodField()
    winner_id = serializers.ReadOnlyField()
    state = serializers.SerializerMethodField()
    started = serializers.ReadOnlyField()
    finished = serializers.ReadOnlyField()
    start_timestamp = serializers.ReadOnlyField()
    stop_timestamp = serializers.ReadOnlyField()
    gamemode = serializers.ReadOnlyField()

    class Meta:
        model = GameModel
        fields = ["id", "winner_id", "state", "started", "finished", "players", "start_timestamp", "stop_timestamp", "gamemode"]

    def get_state(self, instance: GameModel):
        if (instance.finished):
            return "finished"
        if (instance.started):
            return "started"
        return "waiting"

    def get_players(self, instance: GameModel):
        players_data: list = []
        for player_id in instance.get_players_id():
            query: QuerySet = User.objects.filter(pk = player_id)
            username: str = "Deleted User"
            if (query.exists()):
                username = query[0].username
            
            data: dict = {
                "id": player_id,
                "username": username,
                "score": instance.get_score_by_player_id(player_id)
            }
            
            players_data.append(data)
        
        return players_data