extends Marker3D

@onready var hat_anchor = self
var current_hat: Node3D
var hat_index := 0
var hat_scenes: Array[PackedScene] = []

@export var hats_folder := "res://hat_scenes/"
@export var cycle_interval := 3.0

func _ready():
	load_hat_scenes(hats_folder)
	if hat_scenes.size() > 0:
		equip_hat(hat_scenes[hat_index])
		start_cycling()
	else:
		push_warning("No hat scenes found in: " + hats_folder)

func load_hat_scenes(path: String):
	var dir := DirAccess.open(path)
	if dir == null:
		push_error("Could not open hat folder: " + path)
		return

	dir.list_dir_begin()
	while true:
		var file_name = dir.get_next()
		if file_name == "":
			break
		if dir.current_is_dir():
			continue
		if file_name.ends_with(".tscn"):
			var scene_path = path.path_join(file_name)
			var hat_scene = load(scene_path)
			if hat_scene is PackedScene:
				hat_scenes.append(hat_scene)
	dir.list_dir_end()
	hat_scenes.sort_custom(func(a, b): return a.resource_path < b.resource_path)
	
func start_cycling():
	var timer = Timer.new()
	timer.wait_time = cycle_interval
	timer.autostart = true
	timer.one_shot = false
	timer.timeout.connect(_on_cycle_timeout)
	add_child(timer)

func _on_cycle_timeout():
	if hat_scenes.size() == 0:
		return
	hat_index = (hat_index + 1) % hat_scenes.size()
	equip_hat(hat_scenes[hat_index])

func equip_hat(scene: PackedScene):
	if current_hat:
		current_hat.queue_free()
	var hat = scene.instantiate()
	hat_anchor.add_child(hat)
	current_hat = hat
