extends Node

var disposable_player: AudioStreamPlayer

onready var players: Dictionary = {}
onready var static_player: AudioStreamPlayer = $StaticPlayer


# Plays sound with the static player, interrupting sounds if currently playing
func play_sound(
	sound_name: String,
	attenuation: float = 0.0,
	random_pitch = false,
	pitch = 1.0,
	start_time = 0.0,
	bus: String = "Effects"
) -> void:
	# TODO is it bad to grab the stream each time?
	var stream = GlobalState.sound_library[sound_name]
	if random_pitch:
		stream = AudioStreamRandomPitch.new()
		stream.audio_stream = GlobalState.sound_library[sound_name]
	static_player.stream = stream
	static_player.volume_db = attenuation
	static_player.bus = bus
	static_player.pitch_scale = pitch
	static_player.stream_paused = false
	static_player.play(start_time)


func stop_sound():
	static_player.stream_paused = true


# Mirrors the GlobalAudio Method which can play sounds across scenes
func play_parallel_sound(
	sound_name: String,
	attenuation: float = 0.0,
	random_pitch = false,
	pitch = 1.0,
	start_time = 0.0,
	bus: String = "Effects",
	singleton = false
) -> void:
	if singleton && players.has(sound_name):
		return
	var disposable_player = AudioStreamPlayer.new()
	add_child(disposable_player)
	var stream = GlobalState.sound_library[sound_name]
	if random_pitch:
		stream = AudioStreamRandomPitch.new()
		stream.audio_stream = GlobalState.sound_library[sound_name]
	disposable_player.stream = stream
	disposable_player.volume_db = attenuation
	disposable_player.bus = bus
	disposable_player.pitch_scale = pitch
	disposable_player.play(start_time)
	disposable_player.connect("finished", self, "dispose_parallel_player", [weakref(disposable_player)])
	players[sound_name] = weakref(disposable_player)


func dispose_parallel_player(player: WeakRef) -> void:
	if !player.get_ref():
		return
	player.get_ref().queue_free()


func pause_parallel_sound(sound_name: String):
	if players.has(sound_name) && players[sound_name].get_ref():
		players[sound_name].set_stream_paused(true)


func continue_parallel_sound(sound_name: String):
	if players.has(sound_name) && players[sound_name].get_ref():
		players[sound_name].set_stream_paused(false)


func stop_parallel_sound(sound_name: String):
	if players.has(sound_name) && players[sound_name].get_ref():
		dispose_parallel_player(players[sound_name])
		players.erase(sound_name)
