class_name ServerLobby
extends Node


#region Exports

@export var players : Dictionary[int, PlayerData] = {}

#endregion


#region Variables

var free_lobby_indexs : Array[int] = []

#endregion


#region Signals

signal player_registered()

#endregion


#region Client RPC

@rpc("any_peer", "call_local")
func request_player_register(id: int, username) -> void:
    #only run on the multiplayer instance
    if not multiplayer.is_server():
        return

    player_register.rpc_id(1, id, username)

@rpc("any_peer", "call_local")
func update_client_players(id : int, username : String) -> void:
    if not players.has(id):
        players[id] = PlayerData.new(id, players.size(), username)

    player_registered.emit()

#endregion


#region Server RPC

@rpc("authority", "call_local")
func player_register(id : int, username : String) -> void:
    var lobby_index : int = players.size()
    if free_lobby_indexs.size() != 0:
        lobby_index = free_lobby_indexs.pop_front()

    players[id] = PlayerData.new(id, lobby_index, username)

    #send the entire list for clients that join later
    for player_id in players:
        update_client_players.rpc(player_id, players[player_id].name)

@rpc("authority", "call_local")
func player_unregister(id) -> void:
    free_lobby_indexs.append(players[id].lobby_index)
    players.erase(id)
    player_registered.emit()

@rpc("authority", "call_local")
func players_clear() -> void:
    players.clear()
    player_registered.emit()

#endregion
