extends Node

var players = {}
var current_map: String = ""
var local_player_health = 0
var player_state_global: PlayerState = PlayerState.new()
# Called when the node enters the scene tree for the first time.
@rpc("reliable", "call_local")
func get_player_health(id: int) -> int:
	return players.get(id)["health"]

func _on_connected_ok():
	var player_state := PlayerState.new()
	register_player.rpc_id(1, multiplayer.get_unique_id(), player_state_global.name)
	

@rpc("any_peer", "reliable", "call_remote")
func register_player(id: int, name: String):
	if multiplayer.is_server():
		var player_state := PlayerState.new()
		player_state.id = id
		player_state.name = name
		players[multiplayer.get_remote_sender_id()] = player_state

@rpc("any_peer", "reliable", "call_local")
func remove_player(id: int):
	if multiplayer.is_server():
		if players.has(id):
			players.erase(id)
			


func _on_player_disconnected(id):
	remove_player.rpc_id(1, id)
	
func _on_player_connected(id):
	if multiplayer.is_server():
		print("Player is connected with id: " + str(id))

func _ready() -> void:
	multiplayer.peer_connected.connect(_on_player_connected)
	multiplayer.peer_disconnected.connect(_on_player_disconnected)
	multiplayer.connected_to_server.connect(_on_connected_ok)
	pass # Replace with function body.
	
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass

func set_map(name: String): 
	current_map = name
	
func create_server(player_data: PlayerManager) -> Error: 
	var peer = ENetMultiplayerPeer.new()
	var err = peer.create_server(27015, 30)
	multiplayer.multiplayer_peer = peer
	if err:
		return err
	if not OS.has_feature("dedicated_server"):
		var player_state := PlayerState.new()
		player_state.id = 1
		player_state.name = player_data.name
		players[1] = player_state
	return OK
	
func join_server(player_data: PlayerManager, ip: String, port: int) -> Error:
	var peer = ENetMultiplayerPeer.new()
	print("trying to connect to: " + ip + ":" + str(port))
	var err = peer.create_client(ip, port)
	if err != OK:
		return err
	player_state_global.id = multiplayer.get_remote_sender_id()
	player_state_global.name = player_data.name
	multiplayer.multiplayer_peer = peer
	register_player.rpc_id(1, player_state_global)
	return OK
	
@rpc("authority", "call_remote")
func load_map(map: String):
	get_tree().change_scene_to_file(map)
	
	
func request_data_from_client(id: int):
	send_data_to_server.rpc_id(id)
	
@rpc("any_peer", "call_remote")
func send_data_to_server():
	pass
