@tool
class_name SoundQueue extends Node

@export_range(1, 16) var count: int = 8

var _next: int = 0
var _tries: int = 0
var _players: Array[AudioStreamPlayer] = []

func _ready():
	if Engine.is_editor_hint():
		return
	if get_child_count() == 0:
		push_warning("A SoundQueue has no child AudioStreamPlayer!")
		return
	var child = get_child(0)
	if child is AudioStreamPlayer:
		_players.append(child as AudioStreamPlayer)
		for i in count-1:
			var duplicate_player = (child as AudioStreamPlayer).duplicate()
			add_child(duplicate_player)
			_players.append(duplicate_player)
	
func _get_configuration_warnings():
	if get_child_count() == 0:
		return ["An AudioStreamPlayer must be set as the first child."]
	if not get_child(0) is AudioStreamPlayer:
		return ["The first child is not an AudioStreamPlayer."]

func play_sound(sound: AudioStream):
	var player = _players[_next]
	if player.playing:
		_next+=1
		_next %= _players.size()
		_tries += 1
		if _tries < _players.size():
			play_sound(sound)
		else:
			push_warning("Too many sounds playing!")
	else:
		_tries = 0
		player.stream = sound
		player.play()
		
func _on_sound_queued(sound: AudioStream):
	play_sound(sound)
