class_name SettingsSelector
extends Selector

@export var animation: AnimationPlayer = null
@export_file("*.tscn") var menu_path: String = ""
@export var settings_items: Array[SettingsItem] = []
@export var shader: GBShader = null


func _ready() -> void:
	settings_items[0].current_select = Settings.palette
	settings_items[1].current_select = Settings.screen_mode
	settings_items[2].current_select = Settings.master_volume
	settings_items[3].current_select = Settings.sounds_volume
	settings_items[4].current_select = Settings.music_volume
	item_count = settings_items.size()
	_navigate_item(0)


func _physics_process(_delta: float) -> void:
	if not handle_input():
		return

	if Input.is_action_pressed("left") and navigate_timer >= navigate_delay:
		navigate_timer = 0.0
		var decresed: bool = settings_items[current_item].decrease_option()
		if navigate_sound and decresed:
			PulseSound0.load_and_play(navigate_sound)
		return
	if Input.is_action_pressed("right") and navigate_timer >= navigate_delay:
		navigate_timer = 0.0
		var encrised: bool = settings_items[current_item].encrease_option()
		if navigate_sound and encrised:
			PulseSound0.load_and_play(navigate_sound)
		return
	if Input.is_action_just_pressed("start"):
		if select_sound:
			PulseSound0.load_and_play(select_sound)
		save()


func _on_return() -> void:
	animation.play(&"fade_in")
	await animation.animation_finished
	get_tree().change_scene_to_file(menu_path)


func save() -> void:
	# palette
	Settings.palette = settings_items[0].current_select
	shader.game_boy_palette = Settings.get_current_palette()
	# screen mode
	Settings.screen_mode = Settings.ScreenMode.values()[settings_items[1].current_select]
	# volume
	Settings.master_volume = settings_items[2].current_select
	Settings.sounds_volume = settings_items[3].current_select
	Settings.music_volume = settings_items[4].current_select

	Settings.save_settings()


func _navigate_item(index: int) -> void:
	for i in range(settings_items.size()):
		if index == i:
			settings_items[i].set_selected_text()
		else:
			settings_items[i].set_unselected_text()
	_on_item_navigated(index)
