extends Node

var net = NetworkedMultiplayerENet.new()
var api = MultiplayerAPI.new()
var port = 8081
var maxplayer = 4
export(NodePath) var database

func _ready():
	print('listening to port: ' + str(port))
	net.create_server(port, maxplayer)
	
	self.set_custom_multiplayer(api)
	custom_multiplayer.set_root_node(self)
	custom_multiplayer.set_network_peer(net)
	
	net.connect("peer_disconnected",self,"disc")
	net.connect("peer_connected",self,"conn")
	pass # Replace with function body.

func _process(_delta):
	custom_multiplayer.poll()

var playerphsyics = preload('res://playerphysics.tscn')

func conn(arg):
	print('client connected, id: ' + str(arg))
	yield(get_tree(),"physics_frame")
	rpc_id(0,'ping')
	print('clients connected: ' + str(custom_multiplayer.get_network_connected_peers().size()))
	var instance = playerphsyics.instance()
	instance.name = str(arg)
	$players.add_child(instance)

remote func send_clients():
	rpc_id(api.get_rpc_sender_id(), 'client_data', custom_multiplayer.get_network_connected_peers())

# extra

func disc(arg):
	print('client disconnected, id: ' + str(arg))

remote func latency(arg):
	rpc_id(api.get_rpc_sender_id(), 'returnping', arg)

remote func input_handler(arg):
	var id = api.get_rpc_sender_id()
	if $players.has_node(str(id)):
		$players.get_node(str(id)).input = arg
#	rpc_id(id, 'returnping', arg)

func _physics_process(delta):
	var position_datachunk = {}
	for i in $players.get_children():
		position_datachunk[i.name] = i.global_position
	rpc_id(0, 'player_position', position_datachunk)
	
	var animation_datachunk = {}
	for i in $players.get_children():
		animation_datachunk[i.name] = i.animation
	rpc_id(0, 'player_animation', animation_datachunk)
	
	var enemies_datachunk = {}
	for i in $enemies.get_children():
		enemies_datachunk[i.name] = [i.global_position, i.type]
	rpc_id(0, 'enemies_position', enemies_datachunk)

func player_anim(attack,arg):
	rpc_id( 0,'attack_anim', attack, int(arg) )

func hp_update(vida, id):
	rpc_id( 0,'atr_update', {id:{'hp':vida}})

func kill_update(kill, id):
	rpc_id( 0,'atr_update', {id:{'k':kill}})
