## Handle changing changing menus and running the show/hide animations for each menu.
##   Each menu should extend BaseMenu
class_name PauseMenu
extends Panel


signal open_menu(menu_name: String)


@onready var menu_mapping: Dictionary[String, BaseMenu] = {
	"MainMenu": $MainMenu,
	"SettingsMenu": $SettingsMenu,
	"SavesMenu": $SavesMenu,
}

var _active_menu: String = "MainMenu"
var _next_menu: String = ""


func _ready() -> void:
	open_menu.connect(_on_change_menu)

	for menu: BaseMenu in get_children():
		menu.animation_player.animation_finished.connect(_on_animation_finished)
		menu.pause_menu = self
		menu.init()

	SaveGameManager.create_save.connect(_on_create_save)
	SaveGameManager.load_save.connect(_on_load_save)

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_cancel") and !visible:
		_open_pause_menu()
	elif event.is_action_pressed("ui_cancel") and visible and _active_menu == "MainMenu":
		menu_mapping["MainMenu"].animation_player.play("hide")
	elif event.is_action_pressed("ui_cancel"): ## Always back out to the MainMenu - Future, maybe add _previous_menu to allow backing out to any menu
		open_menu.emit("MainMenu")


## Start the `hide` animation for the current menu.
##   The `show` animation will play after the `hide` has completed, from `_on_animation_finished()`.
func _change_menu(menu_name: String) -> void:
	visible = true
	_next_menu = menu_name
	if _next_menu == "":
		menu_mapping["MainMenu"].animation_player.play("hide")
	else:
		menu_mapping[_active_menu].animation_player.play("hide")

func _close_pause_menu() -> void:
	visible = false
	_next_menu = ""
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	SignalManager.resume_game.emit()

## Run the `show` animation for the next menu
##   If there is no next menu, close the pause menu
func _handle_next_menu() -> void:
	if _next_menu == "":
		_active_menu = "MainMenu"
		_close_pause_menu()
	else:
		_active_menu = _next_menu
		_next_menu = ""
		menu_mapping[_active_menu].animation_player.play("show")

func _open_pause_menu() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
	SignalManager.pause_game.emit()
	menu_mapping["MainMenu"].animation_player.play("show")


## When the hide animation finished, start show `show` animation for the next menu
func _on_animation_finished(animation_name: String) -> void:
	if animation_name == "hide":
		_handle_next_menu()

func _on_change_menu(menu_name: String) -> void:
	_change_menu(menu_name)

func _on_create_save(_save: String) -> void:
	menu_mapping["SavesMenu"].reset_menu()
	_close_pause_menu()

func _on_load_save(_save: String) -> void:
	menu_mapping["SavesMenu"].reset_menu()
	_close_pause_menu()