extends Node

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

func _ready() -> void:
	load_save_data()

func load_save_data() -> void:
	for bus_name in GameState.save_data.audio_bus_volumes:
		_apply_audio_bus_volume(bus_name, GameState.save_data.audio_bus_volumes[bus_name])

func set_audio_bus_volume(bus_name: StringName, linear_value: float) -> void:
	var normalized_bus_name := str(bus_name)
	var clamped_value := clampf(linear_value, MIN_VOLUME, MAX_VOLUME)

	GameState.save_data.audio_bus_volumes[normalized_bus_name] = clamped_value
	_apply_audio_bus_volume(normalized_bus_name, clamped_value)
	GameState.save_game()

func get_audio_bus_volume(bus_name: StringName, default_value: float = 1.0) -> float:
	return float(GameState.save_data.audio_bus_volumes.get(str(bus_name), default_value))

func _apply_audio_bus_volume(bus_name: String, linear_value: float) -> void:
	var bus_index := AudioServer.get_bus_index(bus_name)
	if bus_index == -1:
		return

	var clamped_value := clampf(linear_value, MIN_VOLUME, MAX_VOLUME)
	AudioServer.set_bus_volume_db(bus_index, linear_to_db(clamped_value))
	AudioServer.set_bus_mute(bus_index, is_zero_approx(clamped_value))
