# Hurry Curry! - a game about cooking
# Copyright (C) 2025 Hurry Curry! contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
extends Node
class_name PlayRandom

@export var volume_db := 0.0
@export var enable_attenuations := false
@export var randomize_pitch := true

var autoplay := false
var manual_setup_called := false
var sounds = []

func _ready():
	if manual_setup_called:
		return
	sounds = get_children()
	for s: AudioStreamPlayer3D in sounds:
		configure_player(s)

func setup(new_sounds: Array[AudioStream]):
	# new_sounds should be an array of AudioStream
	manual_setup_called = true
	for s in new_sounds:
		var player = AudioStreamPlayer3D.new()
		player.stream = s
		player.volume_db = volume_db
		configure_player(player)
		add_child(player)
		sounds.append(player)

func configure_player(player):
	player.finished.connect(sound_finished)
	player.volume_db = volume_db
	
	if not enable_attenuations:
		player.attenuation_filter_cutoff_hz = 20500

func play_random():
	if sounds.size() == 0: return
	
	var s = sounds[randi_range(0, sounds.size() - 1)]
	if randomize_pitch:
		s.pitch_scale = randf_range(0.9, 1.1)
	s.play()

func stop_all():
	for s in sounds:
		s.stop()

func start_autoplay():
	if autoplay: return
	autoplay = true
	play_random()

func stop_autoplay():
	autoplay = false

func sound_finished():
	if autoplay:
		play_random()
