## Handle changing of pause menus
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.load_save.connect(_on_load_save)
	SaveGameManager.create_save.connect(_on_create_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"):
		menu_mapping[_active_menu].animation_player.play("hide")


## The animation to show the next menu will take place in _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
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	_next_menu = ""
	SignalManager.resume_game.emit()

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, we can move on to opening the next menu
func _on_animation_finished(animation_name: String) -> void:
	if animation_name == "hide" and _next_menu == "":
		_active_menu = "MainMenu"
		_close_pause_menu()
	elif animation_name == "hide":
		_active_menu = _next_menu
		_next_menu = ""
		menu_mapping[_active_menu].animation_player.play("show")

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()