extends Node
class_name GameServer

@export var port: int = 27015
@export var player_limit: int = 30
@export var current_map: String = "lowpoly_tdm_2"

@export var current_player_data := PlayerData.new()

# -- This variable should store all the active players
var players: Dictionary = {}

func _ready() -> void:
	multiplayer.peer_connected.connect(_on_player_connected)
	multiplayer.peer_disconnected.connect(_on_player_disconnected)
	multiplayer.connected_to_server.connect(_on_connected_to_server)
	

func _on_player_disconnected(id) -> void:
	logger.info("player is disconnected with id: " + str(id))
	
	
func _on_player_connected(id) -> void:
	if multiplayer.is_server():
		logger.info("player is connected with id: " + str(id))

func _on_connected_to_server() -> void:
	logger.info("connection is successful, sending info")
	register_player.rpc_id(1, multiplayer.get_unique_id(), current_player_data.username)

func create_server(server_only: bool = false) -> Error:
	var peer := ENetMultiplayerPeer.new()
	logger.info("starting a server the port: " + str(port))
	var err := peer.create_server(port, player_limit)
	multiplayer.multiplayer_peer = peer
	if err:
		return err
	if !server_only:
		var player_data := PlayerData.new()
		player_data.id = 1
		logger.warning("TODO: player name is not yet implemented")
		player_data.username = "dummy"
		players[1] = player_data
	return OK
	
func join_server(ip: String, port: int) -> Error:
	var peer = ENetMultiplayerPeer.new()
	logger.info("trying to connect to: " + ip + ":" + str(port))
	var err = peer.create_client(ip, port)
	if err != OK:
		return err
	multiplayer.multiplayer_peer = peer
	return OK

@rpc("any_peer", "reliable", "call_remote")
func register_player(id: int, name: String):
	if multiplayer.is_server():
		logger.info("registering player: " + str(id))
		var player_data := PlayerData.new()
		player_data.id = id
		player_data.username = name
		players[multiplayer.get_remote_sender_id()] = player_data
		logger.info("player " + str(id) + " is registered")
	else: 
		logger.debug("register player is supposed to be executed on the server")

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass
