class_name VolumeSlider
extends HSlider


## A normal slider that automatically changes the volume of the given [param bus] in
## the given [param bus_layout].
## This slider will automatically load and save it's value when it enters the tree
## or changes it's value.[br]
## INFO: You don't need to change [param min_value] and [param max_value], the calculations
## towards [param volume_db] are automatically being done.

## The bus that get's it's volume changed.
@export var bus: StringName = &"Master"
@export var auto_set_muted: bool = false
@export var min_volume: float = 0.0
@export var max_volume: float = 1.0
@export var default_volume: float = 1.0
## The audio bus layout that get's affected.
#@export var bus_layout: AudioBusLayout = preload("res://resources/default_bus_layout.tres")


func _ready() -> void:
	value_changed.connect(func(_value_changed: bool) -> void:
		SettingsManager.set_setting(&"audio", bus, remap(value, min_value, max_value, 0.0, 1.0), true)
	)

	if not value_changed.is_connected(set_volume):
		value_changed.connect(set_volume)

	var err: float = SettingsManager.get_setting(&"audio", bus)

	var new_value: float = remap(err, 0.0, 1.0, min_value, max_value)
	set_value_no_signal(new_value)
	set_volume(new_value)
	value_changed.emit(value)


## Set's the volume on the audio bus given by [param bus] to the volume_range (Range from 0 to 100).[br]
## Note that this won't change [param value].
func set_volume(volume_range: float) -> void:
	volume_range = remap(volume_range, min_value, max_value, min_volume, max_volume)
	var new_volume: float = linear_to_db(volume_range)
	var bus_idx: int = AudioServer.get_bus_index(bus)

	AudioServer.set_bus_volume_db(bus_idx, new_volume)
	if auto_set_muted:
		AudioServer.set_bus_mute(bus_idx, is_zero_approx(volume_range))


#func save_volume(volume_range: float) -> void:
	#OptionSaver.save_option("audio", bus, (volume_range / max_value))
