extends VBoxContainer

class_name AudioOption

const MIN_VOLUME: float = 0.0
const MAX_VOLUME: float = 1.0

@export var bus_name: StringName = &"Master"
@export var label_text: String = "Master Volume"
@export_range(0.0, 1.0, 0.01) var default_volume: float = 1.0

@onready var label: Label = $Label
@onready var slider: HSlider = $HSlider

func _ready() -> void:
	slider.min_value = MIN_VOLUME
	slider.max_value = MAX_VOLUME
	slider.step = 0.01
	slider.value_changed.connect(_on_slider_value_changed)
	refresh()

func refresh() -> void:
	label.text = label_text

	if not has_bus():
		slider.set_value_no_signal(default_volume)
		slider.editable = false
		label.text = "%s (bus missing)" % label_text
		return

	slider.editable = true
	var saved_volume := AudioManager.get_audio_bus_volume(bus_name, default_volume)
	slider.set_value_no_signal(saved_volume)
	apply_current_value()

func reset_to_default() -> void:
	slider.value = default_volume

func apply_current_value() -> void:
	_set_bus_volume(slider.value)

func has_bus() -> bool:
	return get_bus_index() != -1

func get_bus_index() -> int:
	return AudioServer.get_bus_index(bus_name)

func _set_bus_volume(linear_value: float) -> void:
	if not has_bus():
		return

	var clamped_value := clampf(linear_value, MIN_VOLUME, MAX_VOLUME)
	AudioManager.set_audio_bus_volume(bus_name, clamped_value)

func _on_slider_value_changed(value: float) -> void:
	_set_bus_volume(value)
