extends Node

var num_players = 8
var bus = "master"

var available = []
var queue = []

# Track which sounds are currently playing
var currently_playing: Dictionary = {}


func _ready():
	for i in num_players:
		var player = AudioStreamPlayer.new()
		add_child(player)

		player.bus = bus
		player.finished.connect(_on_stream_finished.bind(player))

		available.append(player)


func _on_stream_finished(player: AudioStreamPlayer) -> void:
	# Mark sound as no longer playing
	if player.stream and player.stream.resource_path != "":
		currently_playing[player.stream.resource_path] = false

	available.append(player)


# Optional volume + optional overlap control
func play(sound_path: String, volume_db: float = 0.0, allow_overlap: bool = false) -> void:
	# If overlap is NOT allowed, skip if already playing
	if not allow_overlap and currently_playing.get(sound_path, false):
		return

	# Mark as playing
	currently_playing[sound_path] = true

	# Queue the sound
	queue.append({
		"path": sound_path,
		"volume": volume_db
	})


func _process(_delta):
	if queue.is_empty() or available.is_empty():
		return

	var data = queue.pop_front()
	var player = available.pop_front()

	player.stream = load(data["path"])
	player.volume_db = data["volume"]
	player.play()
