class_name Screens
extends CanvasLayer

signal game_started
signal game_ended

var current_screen : ScreenBase = null

@onready var title_screen: ScreenBase = $TitleScreen
@onready var failure_screen: ScreenBase = $FailureScreen
@onready var pause_screen: ScreenBase = $PauseScreen
@onready var success_screen: ScreenBase = $SuccessScreen


func _ready() -> void:
	# Ensure that the UI is always processing.
	process_mode = PROCESS_MODE_ALWAYS
	
	# Register all of our custom button's signals and handle them here
	# NOTE: Normally, we'd make individual scripts for screens within the canvas, 
	# 		then handle the behaviours there, but this will suffice for the game jam's simple UI system
	_connect_signals()
	
	# Begin the game with our start screen!
	_switch_screen(title_screen)


func pause_game() -> void:
	_switch_screen(pause_screen)


func failure() -> void:
	# Update scores an the like from here
	_switch_screen(failure_screen)


func success() -> void:
	_switch_screen(success_screen)


func _switch_screen(new_screen) -> void:
	if current_screen:
		var fade_out_tween = current_screen.fade_out()
		await fade_out_tween.finished
		current_screen.visible = false
	
	current_screen = new_screen
	
	if current_screen:
		var appear_tween = current_screen.fade_in()
		await appear_tween.finished
		current_screen.get_tree().call_group(GameConstants.GROUP_BUTTONS, "set_disabled", false)


func _connect_signals() -> void:
	var buttons : Array[Node] = get_tree().get_nodes_in_group(GameConstants.GROUP_BUTTONS)
	if not buttons.is_empty():
		for button in buttons:
			# Connect custom button signals here!
			if button is ButtonBase:
				button.clicked.connect(_on_button_pressed)


func _on_button_pressed(button) -> void:
	match button.name:
		GameConstants.BUTTON_START, GameConstants.BUTTON_RETRY:
			_switch_screen(null)
			game_started.emit()
		GameConstants.BUTTON_BACK_TO_TITLE:
			_switch_screen(title_screen)
			game_ended.emit()
		GameConstants.BUTTON_RESUME:
			get_tree().paused = false
			_switch_screen(null)
			
