extends AudioStreamPlayer

const CONFIG_PATH := "user://settings.cfg"
const CONFIG_SECTION := "audio"
const CONFIG_KEY_VOLUME := "menu_sfx_volume"
const CONFIG_KEY_MUTED := "menu_sfx_muted"
const DEFAULT_VOLUME := 0.7

var _user_volume_linear: float = DEFAULT_VOLUME
var _is_muted: bool = false

func _ready() -> void:
	_load_settings()
	_apply_volume()

func play_hover() -> void:
	if stream == null or _is_muted or _user_volume_linear <= 0.0:
		return
	play(0.0)

func set_user_volume(value: float) -> void:
	var clamped_value: float = clamp(value, 0.0, 1.0)
	if is_equal_approx(_user_volume_linear, clamped_value):
		return
	_user_volume_linear = clamped_value
	_apply_volume()
	_save_settings()

func get_user_volume() -> float:
	return _user_volume_linear

func set_user_muted(muted: bool) -> void:
	if _is_muted == muted:
		return
	_is_muted = muted
	_apply_volume()
	_save_settings()
	if _is_muted:
		stop()

func is_user_muted() -> bool:
	return _is_muted

func _apply_volume() -> void:
	if _is_muted or _user_volume_linear <= 0.0:
		volume_db = -80.0
	else:
		volume_db = linear_to_db(_user_volume_linear)

func _load_settings() -> void:
	var config: ConfigFile = ConfigFile.new()
	var err: int = config.load(CONFIG_PATH)
	if err == OK:
		_user_volume_linear = clamp(float(config.get_value(CONFIG_SECTION, CONFIG_KEY_VOLUME, DEFAULT_VOLUME)), 0.0, 1.0)
		_is_muted = bool(config.get_value(CONFIG_SECTION, CONFIG_KEY_MUTED, false))
	elif err == ERR_DOES_NOT_EXIST:
		_user_volume_linear = DEFAULT_VOLUME
		_is_muted = false
	else:
		push_warning("Failed to load settings.cfg: %s" % err)
		_user_volume_linear = DEFAULT_VOLUME
		_is_muted = false

func _save_settings() -> void:
	var config: ConfigFile = ConfigFile.new()
	var err: int = config.load(CONFIG_PATH)
	if err != OK and err != ERR_DOES_NOT_EXIST:
		push_warning("Failed to load settings.cfg before saving: %s" % err)
		config = ConfigFile.new()
	elif err != OK:
		config = ConfigFile.new()
	config.set_value(CONFIG_SECTION, CONFIG_KEY_VOLUME, _user_volume_linear)
	config.set_value(CONFIG_SECTION, CONFIG_KEY_MUTED, _is_muted)
	var save_err: int = config.save(CONFIG_PATH)
	if save_err != OK:
		push_warning("Failed to save settings.cfg: %s" % save_err)
