class_name PlayerSpawnerController extends Node3D


func _get_spawner() -> MultiplayerSpawner:
	return $MultiplayerSpawner
	
func _get_root() -> Node3D:
	return $Players

# -- Spawn a player node and sync it across all peers
func spawn_players(spawn_location: SpawnController, id: int) -> Error:
	if multiplayer.is_server():
		var char : PlayerPlaceholder = null
		var player_data: PlayerData = GameServerAutoload.players[id]
		char = ResourceLoader.load("res://scenes/player/placeholder.tscn").instantiate()
		char.name = "PlayerPlaceholder_" + str(player_data.id)
		var new_position: Vector3 = spawn_location.get_spawner(SpawnController.Sides.BLUE)
		char.global_position = new_position
		char.owner_id = id
		_get_root().add_child(char)
		return OK
	return ERR_UNAUTHORIZED
	
func remove_player(id: int) -> Error:
	if multiplayer.is_server():
		var found_childen: Array[Node] =_get_root().get_children()
		for found_child in found_childen:
			if found_child.owner_id:
				if found_child.owner_id == id:
					found_child.queue_free()
		return OK
	return ERR_UNAUTHORIZED

func get_player_node(id: int) -> PlayerPlaceholder:
	var nodes: Array[Node] = _get_root().get_children().filter(func(x: PlayerPlaceholder): return x.owner_id == id)
	if nodes.size() > 0:
		return nodes[0]
	return null
