extends Node

signal connection_failed()
signal connection_succeeded()
signal server_disconnected()


func join_game(ip, port:int):
	get_tree().connect("connected_to_server", self, "_connected_ok")
	get_tree().connect("connection_failed", self, "_connected_fail")
	get_tree().connect("server_disconnected", self, "_server_disconnected")
	gamestate.connect("game_ended",self,"_game_ended")
	var host = NetworkedMultiplayerENet.new()
	host.create_client(ip, port)
	get_tree().set_network_peer(host)


func _connected_ok():
	gamestate.rpc("set_player", get_tree().get_network_unique_id())
	emit_signal("connection_succeeded")


func _connected_fail():
	get_tree().disconnect("connected_to_server", self, "_connected_ok")
	get_tree().disconnect("connection_failed", self, "_connected_fail")
	get_tree().disconnect("server_disconnected", self, "_server_disconnected")
	get_tree().set_network_peer(null)
	emit_signal("connection_failed")


func _server_disconnected():
	gamestate.quit_game()
	emit_signal("server_disconnected")


func _game_ended():
	get_tree().disconnect("connected_to_server", self, "_connected_ok")
	get_tree().disconnect("connection_failed", self, "_connected_fail")
	get_tree().disconnect("server_disconnected", self, "_server_disconnected")
	
	gamestate.disconnect("game_ended",self,"_game_ended")
	
	get_tree().set_refuse_new_network_connections(false)
	get_tree().set_network_peer(null)