extends Node

@onready var control_base: Control = $CanvasLayer/ControlBase
@onready var button_play: Button = $CanvasLayer/ControlBase/VBoxContainer/ButtonPlay
@onready var settings: SettingsUI = $CanvasLayer/SettingsUI
@onready var credits: Control = $CanvasLayer/Credits
@onready var help: Control = $CanvasLayer/Help
@onready var level_select: Control = $CanvasLayer/LevelSelect
@onready var level_select_grid_container: GridContainer = $CanvasLayer/LevelSelect/MarginContainer/VBoxContainer/GridContainer
const LEVEL_SELECT_CONTAINER: PackedScene = preload("res://ui/level_select_container.tscn")

func _ready():
	control_base.show()
	credits.hide()
	help.hide()
	level_select.hide()
	button_play.grab_focus()
	init_level_select()

func init_level_select():
	for key in SavegameManager.level_information.keys():
		var level_select_container: Node = LEVEL_SELECT_CONTAINER.instantiate()
		level_select_grid_container.add_child(level_select_container)
		level_select_container.initialize(key)
	pass

func _process(_delta):
	if Input.is_action_just_pressed("pause"):
		if credits.visible:
			_on_button_back_from_credits_pressed()
		elif help.visible:
			_on_button_back_from_help_pressed()
		elif level_select.visible:
			_on_button_back_from_level_select_pressed()

func _on_button_play_pressed():
	if SavegameManager.any_level_has_been_won():
		# TODO show level select
		#get_tree().change_scene_to_file("res://levels/level_1.tscn")
		level_select.show()
		control_base.hide()
		$CanvasLayer/LevelSelect/MarginContainer/VBoxContainer/ButtonBackFromLevelSelect.grab_focus()
		#get_tree().change_scene_to_file("res://levels/level_1.tscn")
		#print("WON lEVEL")
	else:
		# Start directly first level
		get_tree().change_scene_to_file("res://levels/level_1.tscn")
		print("no level won, starting first level directly")

func _on_button_settings_pressed():
	control_base.hide()
	settings.show()

func _on_button_credits_pressed():
	credits.show()
	control_base.hide()
	$CanvasLayer/Credits/ButtonBackFromCredits.grab_focus()

func _on_button_quit_pressed():
	get_tree().quit()

func _on_settings_ui_back_button_pressed():
	settings.hide()
	control_base.show()
	button_play.grab_focus()

func _on_button_back_from_credits_pressed():
	credits.hide()
	help.hide()
	level_select.hide()
	control_base.show()
	button_play.grab_focus()


func _on_button_back_from_level_select_pressed() -> void:
	control_base.show()
	credits.hide()
	level_select.hide()
	button_play.grab_focus()

func _on_button_back_from_help_pressed() -> void:
	help.hide()
	control_base.show()
	button_play.grab_focus()


func _on_button_help_pressed() -> void:
	help.show()
	control_base.hide()
	$CanvasLayer/Help/ButtonBackFromHelp.grab_focus()
