extends Node

var child_level : Level
@export var player : PlayerController

func _ready():
	SceneChanger.level_manager = self
	SignalBus.change_level.connect(_next_level)
	_set_level()

func _exit_tree() -> void:
	SignalBus.change_level.disconnect(_next_level)

func _next_level():
	var next_level = Globals.save_game.level + 1
	Globals.save_game.level = next_level as Utils.LEVELS
	SceneChanger.change_level()

func change():
	child_level.queue_free()
	_set_level()

func _set_level():
	var new_child = _get_level()
	add_child(new_child)
	child_level = new_child
	player.can_jump_in_level = new_child.level_type != Utils.LEVEL_TYPE.SAVE
	player.position = new_child.player_spawn_point.position

func _get_level():
	return load(Utils.LEVEL_PATHS[Globals.save_game.level]).instantiate()
