extends Node2D

var Map = preload("Map.tscn")
var Player = preload("Player.tscn")
var RemotePlayer = preload("RemotePlayer.tscn")
var mpclient = preload("lib/client_ui.tscn")
# Declare member variables here. Examples:
# var a = 2
# var b = "text"

var map
var player
var remoteplayers = {}

# Called when the node enters the scene tree for the first time.
func _ready():
	map = Map.instance()
	map.init()
	map.getMap("https://hacknplay.org/maps/test/main.json")
	map.name="Map"
	map.owner=self
	add_child(map, true)
	spawn_player()
	mpclient = mpclient.instance()
	add_child(mpclient)
	#get_tree().set_network_peer(mpclient.client.rtc_mp)
	mpclient.client.rtc_mp.connect("peer_connected", self, "spawn_remotePlayer")
	mpclient.client.rtc_mp.connect("peer_disconnected", self, "remove_remotePlayer")
	mpclient.client.connect("connected", self, "set_id")

# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass

func spawn_player():
	print(get_children())
	while not map.mapImported:
		yield(Engine.get_main_loop(), "idle_frame")
		
	#print(get_node("Map/TMX/start").tile_set.get_used_tiles())
	#breakpoint
	
	player = Player.instance()
	player.owner = self
	player.name = "Player"
	get_node("Map/TMX/floorLayer").add_child(player, true)
	get_node("Map/TMX/floorLayer/Player/Camera2D").current = true
	
func set_id(id):
	get_node("Map/TMX/floorLayer/Player").id = id
	 
func spawn_remotePlayer(id):
	var remoteplayer = RemotePlayer.instance()
	remoteplayer.owner = self
	remoteplayer.name = "Player "+str(id)
	remoteplayer.id = id
	get_node("Map/TMX/floorLayer").add_child(remoteplayer, true)
	remoteplayers[id] = remoteplayer
	
func remove_remotePlayer(id):
	print("removing player", id)
	remoteplayers[id].queue_free()

func disconnected():
	for remoteplayer in remoteplayers:
		remove_remotePlayer(remoteplayer.id)
