class_name Level
extends Node

var player_scene : PackedScene = preload("res://Scenes/Mobs/character.tscn")

@export var lobby : Lobby

var spawnid : int = 0

func _ready() -> void:
	spawn_player.rpc_id(1, 1)

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

	#don't spawn an already spawned player
	if get_node_or_null("Player" + str(id)) != null:
		return

	spawn_player.rpc_id(1, id)

@rpc("any_peer", "call_local")
func spawn_player(id: int) -> void:
	var new_player : Player = player_scene.instantiate()

	new_player.name = "Player" + str(id)
	print("Spawning ID: ", id)
	add_child(new_player)
	var spawn_point: Marker3D = lobby.spawnpoints[spawnid]
	print(spawn_point.global_position)
	new_player.teleport_player.rpc(spawn_point.global_position, spawn_point.rotation)
	spawnid += 1

@rpc("authority", "call_local")
func remove_client_from_server(id : int) -> void:
	var disconnected_player : Player = get_node("Player" + str(id))
	spawnid = 1
	remove_child.call_deferred(disconnected_player)
	disconnected_player.queue_free()

@rpc("any_peer", "call_local")
func disconnect_from_server():
	remove_players()
	spawnid = 0
	# reset map
	print("Disconnect: ", multiplayer.get_unique_id())
	request_spawn_player.rpc(1)



func remove_players(remove_host : bool = true) -> void:
	for child in get_children():
		if child is Player:
			if !remove_host and child.name == "Player1":
				continue
			remove_child(child)
			child.queue_free()
