extends Node


signal player_spawn
# The player scene (which we want to configure for replication).
const Player = preload("res://entities/Player.tscn")
@onready var NetworkingRoot = get_node("/root/Game/Networking")


func start_network(server: bool, ip="localhost"):
	var peer = ENetMultiplayerPeer.new()
	if server:
		peer.create_server(27015)
		# Listen to peer connections, and create new player for them
		multiplayer.peer_connected.connect(create_player)
		# Listen to peer disconnections, and destroy their players
		multiplayer.peer_disconnected.connect(destroy_player)
		multiplayer.set_multiplayer_peer(peer)
		create_player()
	else:
		peer.create_client(ip, 27015)
		multiplayer.set_multiplayer_peer(peer)
	
func add_network_entity(path):
	var spawner = NetworkingRoot.get_node("Networking") as MultiplayerSpawner
	spawner.add_spawnable_scene(path)
	
	
func create_player(id=1):
	# Instantiate a new player for this client.
	var p = Player.instantiate()
	# Sets the player name (only sent during spawn).
	#p.player_name = "Player %d" % id
	# Set a random position (sent on every replicator update).
	#p.position = Vector2(randi() % 500, randi() % 500)
	# Add it to the "Players" node.
	# We give the new Node a name for easy retrieval, but that's not necessary.
	p.name = str(id)
	#p.set_multiplayer_authority(id)
	NetworkingRoot.add_child(p)
	p.init()

func destroy_player(id):
	# Delete this peer's node.
	NetworkingRoot.get_node(str(id)).queue_free()
