extends Node

var sound_volume = 80
var music_volume = 80

var volume = {"sound":0, "music":0}
var muted = {"sound": false, "music":false}

var playing_song = ""

func reset_players():
	$tween.stop_all()
	for p in $players.get_children():
		p.stop()
		p.volume_db = 0
		p.stream = null

func is_music_playing():
	if $music_player.playing:
		return $music_player.get_stream_playback()

func play_sound(s, loop):
	var stream = $sounds.get_resource(s)
	var player = get_free_player()
	if !loop:
		player.stream = stream
		player.play()
	else:
		stream.loop_mode = AudioStreamSample.LOOP_FORWARD
		stream.loop_begin = 0
		stream.loop_end = stream.get_length() * stream.mix_rate
		player.stream = stream
		player.play()
		return player
	
func stop_playing(player, fade, duration):
	if fade:
		var tween = $tween
		tween.interpolate_property(player, "volume_db", 0, -32, duration, Tween.TRANS_LINEAR, Tween.EASE_IN)
		tween.start()
		yield(tween,"tween_completed")
	player.stop()
	player.volume_db = 0
	player.stream = null

func get_free_player():
	for p in $players.get_children():
		if p.playing:
			continue
		else:
			return p
	return $players.get_child(0)
	
func play_music(m, l):
	if playing_song == m:
		return
	var music = load("res://audio/music/" + m + ".ogg")
	playing_song = m
	music.loop = l
	$music_player.stream = music
	$music_player.play()
	
func change_music_volume(v):
	music_volume = v
	AudioServer.set_bus_volume_db(2, range_lerp(music_volume, 0, 100, -50, 12))
	
func change_sound_volume(v):
	sound_volume = v
	AudioServer.set_bus_volume_db(1, range_lerp(sound_volume, 0, 100, -50, 12))
	
func mute_bus(bus, condition):
	muted[AudioServer.get_bus_name(bus)] = condition
	AudioServer.set_bus_mute(bus, condition)

func get_stream(s):
	return $sounds.get_resource(s)
	

