extends Node

const SERVER_PORT = 14600
const MAX_PLAYERS = 1000

func _ready():
	get_tree().connect("network_peer_connected", self, "_player_connected")
	get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
	start_server()

func start_server():
	var peer = WebSocketServer.new()
	var result = peer.listen(SERVER_PORT, PoolStringArray(), true)
	get_tree().connect("server_disconnected", self, "_close_network")
	get_tree().set_network_peer(peer)
	print("Server started.")
	
	if result != OK:
		print("Failed creating the server.")
		return
	else:
		print("Created the server.")
	
	get_tree().set_network_peer(peer)

func _player_connected(id):
	NetworkingSync._players_online.append(id)
	NetworkingSync._number_of_online_players = len(get_tree().get_network_connected_peers())

func _player_disconnected(id):
	NetworkingSync._players_online.erase(id)
	NetworkingSync._number_of_online_players = len(get_tree().get_network_connected_peers())
	if id in NetworkingSync._open_games:
		NetworkingSync.remove_game_from_game_list(id)
	
