extends Node
class_name MapController

const PLAYER_SPAWNER: String = "res://scenes/maps/base/player_spawner/player_spawner.tscn"
const BULLET_SPAWNER: String = "res://scenes/maps/base/bullet_spawner/bullet_spawner.tscn"

var player_spawner: PlayerSpawnerController
var bullet_spawner: BulletSpawnerController
var client_node: Node3D

@onready var spawn_locations: SpawnController = $SpawnLocations

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	# add player spawner
	var err: Error = OK
	
	err = _add_player_spawner()
	if err != OK:
		push_error("Couldn't load player spawner")
	
	err = _add_bullet_spawner()
	if err != OK:
		push_error("Couldn't load bullet spawner")
	
	# Adding a node that should be used by the clients
	client_node = Node3D.new()
	client_node.name = "ClientNode"
	add_child(client_node)
	# add objects spawner
	if not OS.has_feature("dedicated_server"):
		_request_spawn.rpc_id(1)
	
	
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if multiplayer.is_server():
		pass
		#var active_players = player_spawner._get_root().get_children()
		#for n in active_players:
			#if not Server.players.has(n.owner_id):
				#_remove_player(n.owner_id)

@rpc("call_local", "reliable", "any_peer")
func _request_spawn():
	var id: int = multiplayer.get_remote_sender_id()
	_spawn_player(id)
	_spawn_player_controller_node.rpc_id(id)

func _spawn_player(id: int):
	player_spawner.spawn_players(spawn_locations, id)

@rpc("call_local", "reliable", "any_peer")
func _spawn_player_controller_node():
	var path := "res://scenes/player/player_input.tscn"
	var scene: PackedScene = ResourceLoader.load(path)
	var controller_scene: PlayerPlaceholder = player_spawner.get_player_node(multiplayer.get_unique_id())
	var player_node: PlayerInputController = scene.instantiate()
	player_node.controlled_node = controller_scene
	client_node.add_child(player_node)
	

func _remove_player(id: int):
	player_spawner.remove_player(id)
	
func _add_player_spawner() -> Error :
	if not ResourceLoader.exists(PLAYER_SPAWNER):
		return ERR_DOES_NOT_EXIST
	var scene: PackedScene = ResourceLoader.load(PLAYER_SPAWNER)
	if not scene.can_instantiate():
		return ERR_CANT_OPEN
	
	var node: Node3D = scene.instantiate()
	add_child(node)
	player_spawner = node
	return OK
	
func _add_bullet_spawner() -> Error :
	if not ResourceLoader.exists(BULLET_SPAWNER):
		return ERR_DOES_NOT_EXIST
	var scene: PackedScene = ResourceLoader.load(BULLET_SPAWNER)
	if not scene.can_instantiate():
		return ERR_CANT_OPEN
	var node: BulletSpawnerController = scene.instantiate()
	add_child(node)
	bullet_spawner = node
	return OK
	
# -- TODO: Better bullet naming handler
var bullet_amount: int = -2147483647
func spawn_bullet(starting_point: Node3D, speed: int, damage: int):
	bullet_spawner.spawn_bullet(starting_point, speed, damage)
