extends Node

signal refresh_lobby
signal server_closed
signal connection_successful
signal connection_failed

export var SERVER_PORT = 12345
export var MAX_PLAYERS = 3

enum Role {
	Builder,
	Operator
}

var RoleNames = [
	"Builder",
	"Operator"
]

var players = {}
var my_info = { nickname = "Pl4ceHolder", role = Role.Operator }

func _ready():
	get_tree().connect("network_peer_connected", self, "_player_connected")
	get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
	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")


func host_game(nick):
	my_info.nickname = nick
	var peer = NetworkedMultiplayerENet.new()
	peer.create_server(SERVER_PORT, MAX_PLAYERS)
	get_tree().set_network_peer(peer)


func connect_to_game(nick, server_ip):
	my_info.nickname = nick
	var peer = NetworkedMultiplayerENet.new()
	peer.create_client(server_ip, SERVER_PORT)
	get_tree().set_network_peer(peer)


func reset_connection():
	players.clear()
	get_tree().set_network_peer(null)

func _player_connected(id):
	print("Player connected " + str(id))


func _player_disconnected(id):
	print("Player disconnected " + str(id))
	players.erase(id)
	emit_signal("refresh_lobby")


# Only called by client when connecting to host
func _connected_ok():
	print("registering self")
	rpc("register_player", get_tree().get_network_unique_id(), my_info )
	emit_signal("connection_successful")


func _connected_fail():
	print("Failed to connect to host")
	emit_signal("connection_failed")


func _server_disconnected():
	print("Server disconnected")
	get_tree().has_network_peer(null)
	emit_signal("server_closed")


remote func register_player(id, player_info):
	# Add new player to player dict
	print("Registering player" + str(id))
	players[id] = player_info
	
	# If we are server, tell new client about other players
	if get_tree().is_network_server():
		for player_id in players:
			rpc_id(id, "register_player", player_id, players[player_id])
		
	# Tell gui to update
	emit_signal("refresh_lobby")
