extends Node

var net = NetworkedMultiplayerENet.new()
var api = MultiplayerAPI.new()
var port = 2020
var ip = '104.156.250.247'
# Called when the node enters the scene tree for the first time.
func _ready():
	print('connecting to port: ' + str(port))
	print('at ip: '+ip)
	net.create_client(ip,port)
	
	self.set_custom_multiplayer(api)
	custom_multiplayer.set_root_node(self)
	custom_multiplayer.set_network_peer(net)
	
	net.connect("connection_failed", self, "_On_Connection_Failed")
	net.connect("connection_succeeded", self, "_On_Connection_Succeeded")
	pass # Replace with function body.

func _process(_delta):
	custom_multiplayer.poll()

remote func ping():
	print('messaged received from server')

remote func tokerequest():
	var tk = get_parent().get_node('Loginetcode').token_buffer
	print('tk is ' + tk)
	var username = get_parent().get_node('Loginetcode').username_server
	rpc_id(1,'tokenreply', tk, username)

func _On_Connection_Failed():
	print("Failed to connect to game server")

var playerphsyics = preload('res://playersprite.tscn')
var playerhud = preload('res://hud.tscn')

export var dummy = false

func _On_Connection_Succeeded():
	rpc_id(1,'connected_peer')

remote func _On_Peer_Connected():
	$Input.enabled = true
	print("Succesfully connected to game server")
	if not has_node("players"): return
	request_clients()
	yield(self, 'client_request')
	for x in current_clients:
		gen_objs(playerphsyics,x,$players)
		gen_objs(playerhud,x, $Hud/HBoxContainer)
	
	if dummy:
		rpc_id(1,'makedummmy')

func gen_objs(arg,x, node):
	if not node.has_node(str(x)):
		var instance = arg.instance()
		instance.name = str(x)
		node.add_child(instance)

remote func _On_Player_Disconnect(arg):
	print(str(arg) + ' had left the server')
	var arr = [$players, $Hud/HBoxContainer]
	for x in arr:
		if x.has_node(str(arg)):
			x.get_node(str(arg)).queue_free()

signal client_request
var current_clients = []

func request_clients():
	rpc_id(1,'send_clients')

remote func client_data(arg):
	current_clients = arg
	emit_signal('client_request')

# extra stuff

var ping = 0

func latency_test():
	rpc_id(1,'latency',OS.get_system_time_msecs())

remote func returnping(arg):
	ping = (OS.get_system_time_msecs() - arg)

func send_input(arg):
	rpc_id(1,'input_handler',arg)

remote func player_position(arg):
	if not has_node("players"): return
	for id in arg.keys():
		if $players.has_node(str(id)):
			var node = $players.get_node(str(id))
			if node.global_position.x != arg[id].x:
				node.scale.x = -1 if node.global_position.x > arg[id].x else 1
				node.get_node('Label').scale.x = -1 if node.global_position.x > arg[id].x else 1
			node.global_position = arg[id]

remote func player_animation(arg):
	if not has_node("players"): return
	for id in arg.keys():
		if $players.has_node(str(id)):
			$players.get_node(str(id)).animation  = arg[id]

func reconstruct_int16(bytetest):
	return ((bytetest[0] * 255) + bytetest[1])-32768

var argbuffer
var posbuffer

remote func enemies_position_2(arg):
	if not has_node('enemies'): return
	for i in $enemies.get_children():
		i.hide()
	
	argbuffer = posbuffer
	posbuffer = []
	var sprite = []
	for i in range(0,arg.size(),5):
		var aux =  Vector2( reconstruct_int16([ arg[i] , arg[i+1]]), reconstruct_int16([ arg[i+2] , arg[i+3]]) )
		posbuffer.append(aux)
		sprite.append(arg[i+4])
	
	for i in posbuffer.size():
		$enemies.get_child(i).show()
		$enemies.get_child(i).global_position = posbuffer[i]
	
	for i in sprite.size():
		$enemies.get_child(i).texture = get_node('../Textures').dict[sprite[i]]

remote func attack_anim(arg, id):
	if not has_node("players"): return
	if not $players.has_node(str(id)): return
	$players.get_node(str(id)).get_node('weapon/AnimationPlayer').play(arg)

remote func atr_update(arg):
	if has_node('Hud/HBoxContainer/'+arg.keys()[0]):
		get_node('Hud/HBoxContainer/'+arg.keys()[0])._update(arg.values()[0])

remote func level_up(arg, id):
	if not has_node("players"): return
	$players.get_node(str(id)).level_up_anim()

#powerpick
remote func powerpick(arg , id):
	if has_node('PowerMenu'):
		$PowerMenu/CenterContainer.show()
		print(arg)
		$PowerMenu.showmenu(arg, id)

func players_choice_is(choice, idbuffer):
#	print(choice)
	rpc_id(1,'optionpick',idbuffer, choice)

remote func _On_chat_Message(arg):
	$RichTextLabel.text += arg + "\n"

func chat_messages(arg):
	print(arg)
	$LineEdit.text= ''
	rpc_id(1,'chat_messages', arg)

var usernamelist = {}

remote func _on_usernames(arg):
	for i in arg.keys():
		usernamelist[i] = arg[i]

