extends Node

var fading = false
var animation_time : float
var animation_duration : float
var target_track : AudioStreamPlayer
var previous_tracks : Array

func play(music, offset=0, duration=1):
	print('Play music: ' + music)
	var path = "res://sounds/" + music + ".ogg"
	if !File.new().file_exists(path):
		path = "res://sounds/" + music
		assert(File.new().file_exists(path))
	var stream = load(path)
	
	target_track = get_free_track()
	previous_tracks = get_playing_tracks()
	
	if previous_tracks.size() > 0:
		fading = true
		animation_time = 0
		animation_duration = duration
	
	target_track.stream = stream
	target_track.play(offset)

func fade_out(duration=1):
	target_track = null
	previous_tracks = get_playing_tracks()
	fading = true
	animation_time = 0
	animation_duration = duration

func get_playing_tracks() -> Array:
	var tracks = []
	for track in get_children():
		if track.playing:
			tracks.append(track)
	return tracks

func get_free_track() -> AudioStreamPlayer:
	var free_track = null
	for track in get_children():
		if !track.playing:
			free_track = track
	if free_track == null:
		free_track = AudioStreamPlayer.new()
		print('yo')
		add_child(free_track)
	print(free_track)
	return free_track

func _process(delta):
	if fading:
		animation_time += delta
		var p = clamp(animation_time / animation_duration, 0, 1)
		
		if target_track != null:
			target_track.volume_db = lerp(-90, 0, p)
		for previous_track in previous_tracks:
			previous_track.volume_db = lerp(0, -90, p)
		
		if p == 1:
			fading = false
			for previous_track in previous_tracks:
				previous_track.stop()
				previous_track.queue_free()
