@tool
class_name SaveGameHandle extends CenterContainer

signal picked(save_game: SaveGame)

var has_stage: bool = false:
	set(stage):
		has_stage = stage
		visible = stage
		save_buttons[0].grab_focus()

@export var saves: Array[SaveGame]
var save_buttons: Array[SaveGameDisplay]
@export var update_display: bool:
	set(value):
		load_games()
var scroll_container: ScrollContainer

var create_new_game: bool = false

func _ready() -> void:
	var dir = DirAccess.open(State.user_saves_path)
	print(DirAccess.get_open_error())
	# Invalid Error being raised when Directory does not exist.
	if DirAccess.get_open_error() == ERR_INVALID_PARAMETER:
		dir = DirAccess.open("user://")
		dir.make_dir_recursive(State.user_saves_path)
	load_games()

func load_games():
	var save_game_dir := DirAccess.open(State.user_saves_path)
	var filepaths: PackedStringArray = save_game_dir.get_files()
	
	for path in filepaths:
		if path.ends_with(".json"):
			saves.append(SaveGame.new(path))
	
	saves.append(SaveGame.new())
	
	#purging the current state
	save_buttons = []
	if scroll_container != null:
		scroll_container.free()
	
	scroll_container = ScrollContainer.new()
	
	scroll_container.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
	add_child(scroll_container)
	
	
	for i in range(saves.size()):
		var new_button := SaveGameDisplay.new(saves[i], i+1)
		scroll_container.add_child(new_button)
		save_buttons.append(new_button)
		new_button.pressed.connect(func(): _on_game_picked(i))

func _on_game_picked(id: int):
	if create_new_game:
		if saves[id].current_room == 0:
			picked.emit(id)
		else:
			$Popup.show()
			
	else:
		picked.emit(id)

func pick_slot(create_new_game: bool):
	State.take_stage(self)
	self.create_new_game = create_new_game

func get_most_recent_save() -> SaveGame:
	var most_recent_time := 0.0
	var most_recent_index:int = 0
	for i in range(saves.size()):
		if saves[i].last_saved > most_recent_time and not saves[i].current_room == 0:
			most_recent_index = i
			most_recent_time = saves[i].last_saved
			
	return saves[most_recent_index] if most_recent_time > 0 else SaveGame.new()
