extends Node

const PlayerScene = preload("res://Player.tscn")
var rng = RandomNumberGenerator.new()
func _ready():
	$MultiplayerSpawner.add_spawnable_scene("res://Player.tscn")
	print($MultiplayerSpawner.get_spawnable_scene(0))
	# Start the server if Godot is passed the "--server" argument,
	# and start a client otherwise.
	if Globals.is_server:
		start_network(true)
	else:
		start_network(false)
	

func start_network(server: bool):
	var peer = ENetMultiplayerPeer.new()
	if server:
		multiplayer.peer_connected.connect(self.create_player)
		multiplayer.peer_disconnected.connect(self.destroy_player)
		
		peer.create_server(4242)
		print('server listening on localhost 4242')
	else:
		multiplayer.connected_to_server.connect(self.connected_to_server)
		peer.create_client(Globals.server_ip, 4242)

	multiplayer.set_multiplayer_peer(peer)

func create_player(id):
	#pass
	# Instantiate a new player for this client.
	var p = PlayerScene.instantiate()
	#var p = Node3D.new()

	# Set the name, so players can figure out their local authority
	p.name = str(1)
	print(str(id) + ' just connected')
	
	$NetworkedNodes.add_child(p)

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

func connected_to_server():
	$Pole/Camera3D.queue_free()
