class_name PauseMenuController
extends Node

## Node for opening a pause menu when detecting a 'ui_cancel' event.
@export var pause_menu_packed : PackedScene
@export var focused_viewport : Viewport
@export var player : CharacterBody3D

@export_group("Inputs")
@export var pause:GUIDEAction

var menu_already_open = false

func _ready() -> void:
	pause.triggered.connect(on_input_pause)
	
func on_input_pause():
	if menu_already_open:
		return
		
	menu_already_open = true
	if not focused_viewport:
		focused_viewport = get_viewport()
	var _initial_focus_control = focused_viewport.gui_get_focus_owner()
	var current_menu = pause_menu_packed.instantiate()
	
	current_menu.menu_closing.connect(player.LoadSettings)
	
	get_tree().current_scene.call_deferred("add_child", current_menu)
	await current_menu.tree_exited
	menu_already_open = false
	if is_inside_tree() and _initial_focus_control:
		_initial_focus_control.grab_focus()
