extends Control

@onready
var character_panel: Panel = %CharacterPanel

@onready
var character_grid: GridContainer = %CharacterGridContainer

@onready
var close_timer: Timer = %CloseTimer

signal character_selected(file_name: String)
signal new_new_character_selected(file_name: String)

var character: PackedScene = preload("res://character.tscn")

func _ready() -> void:
	close_timer.timeout.connect(_on_close_timeout)

func select_character(file_name: String) -> void:
	print("select_character")
	character_selected.emit(file_name)

func _on_close_timeout() -> void:
	print("_on_close_timeout!")
	Settings.character_select_open = false
	close_timer.stop()

func load_characters() -> void:
	print("load_characters")
	var fetch_character_list: Callable = func fetch_character_list(list) -> void:
		print("fetch_character_list")
		Settings.delete_children(character_grid)
		if typeof(list) == TYPE_ARRAY:
			for character_name: String in list:
				print("character_name ", character_name)
				var character_box: Character = character.instantiate()
				character_grid.add_child(character_box)
				character_box.custom_minimum_size = Vector2(235, 145)
				character_box.size = Vector2(235, 145)
				character_box.set_character_name(character_name)
				character_box.connect("new_character_selected", _on_character_selected)
	Settings.make_request2("/characters", fetch_character_list, true)

func show_grid() -> void:
	print("show_grid")
	close_timer.stop()
	self.visible = true
	Settings.character_select_open = true

func _on_character_selected(texture: ImageTexture) -> void:
	print("_on_character_selected")
	self.visible = false
	new_new_character_selected.emit(texture)
	close_timer.start()

func _input(event: InputEvent) -> void:
	if self.visible == true:
		if event is InputEventMouseButton && event.is_pressed():
			var evLocal: InputEvent = make_input_local(event)
			if !Rect2(Vector2(0, 0), character_panel.size).has_point(evLocal.position):
				self.visible = false
				Settings.character_select_open = false

func load_characters_local() -> void:
	var characters: DirAccess = DirAccess.open("res://characters/")
	if characters:
		characters.list_dir_begin()
		var file_name: String = characters.get_next()
		while file_name != "":
			file_name = file_name.replace('.import', '') # <--- remove the .import
			if file_name.ends_with(".png"):
				var texture: Resource = load("res://characters/" + file_name)
				var texture_btn: TextureButton = TextureButton.new()
				character_grid.add_child(texture_btn)
				texture_btn.custom_minimum_size = Vector2(80, 40)
				texture_btn.ignore_texture_size = true
				texture_btn.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT
				texture_btn.texture_normal = texture
				texture_btn.pressed.connect(select_character.bind(file_name))
			file_name = characters.get_next()
