extends ScrollContainer

onready var LEVELS_PATH = "res://src/Levels/"
onready var BUTTON_GROUP : ButtonGroup = load("res://src/UserInterface/Screens/MainMenu/LevelSelectButtonGroup.tres")
onready var LEVEL_CHECK_BOX = load("res://src/UserInterface/Screens/MainMenu/LevelCheckBox.tscn")
onready var vbox: VBoxContainer = $VBoxContainer

var prev_checkbox
var selected_button

func _ready() -> void:
	BUTTON_GROUP.connect("pressed", $"%PlayButton", "_level_selection_changed")
	BUTTON_GROUP.connect("pressed", self, "_level_selection_changed")
	_fill_level_list()

func _level_selection_changed(button) -> void:
	selected_button = button

func _input(event: InputEvent) -> void:
	if(event.is_action("ui_accept") && selected_button != null && selected_button.has_focus()):
		$"%PlayButton"._on_button_up()

func _fill_level_list():
	var levels = []
	var dir = Directory.new()
	if dir.open(LEVELS_PATH) == OK:
		dir.list_dir_begin()
		while true:
			var file_name = dir.get_next()
			if file_name == "":
				break
			else:
				if(file_name.ends_with(".tscn")):
					levels.append(file_name)
	if levels.size() != 0:
		_spawn_level_options(levels)

func _spawn_level_options(levels: Array):
	var first = true
	for level in levels:
		if !GlobalState.was_level_touched(LEVELS_PATH + level) && !first:
			continue
		var level_check_box = LEVEL_CHECK_BOX.instance()
		vbox.add_child(level_check_box)
		level_check_box.initialize_with_progress(LEVELS_PATH + level)
		var check_box = level_check_box.get_node("CheckBox")
		check_box.focus_mode = Control.FOCUS_ALL
		check_box.focus_neighbour_left = $"%PlayButton".get_path()
		check_box.text = level.trim_suffix(".tscn")
		check_box.set_button_group(BUTTON_GROUP)
		if first || GlobalState.gsr.last_played_level.ends_with(level):
			$"%PlayButton".focus_neighbour_right = check_box.get_path()
			$"%Controlls".focus_neighbour_right = check_box.get_path()
			$"%Audio".focus_neighbour_right = check_box.get_path()
			$"%QuitButton".focus_neighbour_right = check_box.get_path()
			check_box.pressed = true
			first = false
			yield(get_tree(), "idle_frame")
			ensure_control_visible(check_box)
		if prev_checkbox != null:
			prev_checkbox.focus_neighbour_bottom = check_box.get_path()
			check_box.focus_neighbour_top = prev_checkbox.get_path()
		prev_checkbox = check_box
	return
