extends Node

const MUSIC_PATH := "res://audio/Space Horror InGame Music (Exploration) _Clement Panchout.wav"
const UI_CLICK_SOUND_PATH := "res://audio/817587__silverdubloons__tick06.wav"

var music_player: AudioStreamPlayer
var ui_click_player: AudioStreamPlayer
var click_stream: AudioStream

func _ready():
	music_player = AudioStreamPlayer.new()
	add_child(music_player)

	ui_click_player = AudioStreamPlayer.new()
	ui_click_player.bus = "SFX"
	add_child(ui_click_player)

	click_stream = load(UI_CLICK_SOUND_PATH)

	var orig_stream = _load_stream()
	if not orig_stream:
		push_error("Failed to load music stream: %s" % MUSIC_PATH)
		return

	var stream = orig_stream.duplicate(true) as AudioStream
	_configure_stream_loop(stream)
	music_player.stream = stream
	_configure_audio_bus()

	if SettingsManager.get_setting("music_volume") <= 0:
		return

	_start_music()

func _load_stream() -> AudioStream:
	var res = load(MUSIC_PATH)
	if not res or not res is AudioStream:
		return null
	return res

func _configure_stream_loop(stream: AudioStream) -> void:
	if stream is AudioStreamWAV:
		stream.loop_mode = AudioStreamWAV.LOOP_FORWARD
	elif stream is AudioStreamOggVorbis:
		stream.loop = true

func _configure_audio_bus() -> void:
	music_player.bus = "Music"
	music_player.volume_db = linear_to_db(SettingsManager.get_setting("music_volume"))

func update_music_volume(volume: float) -> void:
	var volume_db = linear_to_db(volume)
	music_player.volume_db = volume_db
	AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Music"), volume_db)

	if volume > 0:
		_start_music()
	else:
		_stop_music()

func _start_music() -> void:
	if music_player.playing:
		return
	music_player.play()

func _stop_music() -> void:
	if not music_player.playing:
		return
	music_player.stop()

func play_ui_click() -> void:
	if not click_stream:
		return
	ui_click_player.stream = click_stream
	ui_click_player.play()
