extends AudioStreamPlayer

const NORMAL_DB := -10.0
const DUCKED_DB := -24.0
const DUCK_IN := 0.15
const DUCK_OUT := 0.4
# these paths wwould need to be updated if renamed or moved
const BARK_PATHS := [
	"../CanvasPanel/ElevatorPanel/SfxRobotDeepBreath",
	"../CanvasPanel/ElevatorPanel/SfxRobotSoundsDifficult",
	"../CanvasPanel/ElevatorPanel/SfxRobotIUnderstand",
	"../CanvasPanel/ElevatorPanel/SfxRobotThankYou",
]

var _barks: Array = []
var _ducked: bool = false
var _tween: Tween
var _started: bool = false

func _ready() -> void:
	volume_db = NORMAL_DB
	finished.connect(play)
	for p in BARK_PATHS:
		var n := get_node_or_null(p)
		if n:
			_barks.append(n)
	EventBus.game_started.connect(_on_game_started)
	EventBus.game_won.connect(_on_game_ended)
	EventBus.game_lost.connect(_on_game_lost)

func _process(_delta: float) -> void:
	if not playing:
		return
	var any := false
	for b in _barks:
		if b.playing:
			any = true
			break
	if any and not _ducked:
		_ducked = true
		_to_db(DUCKED_DB, DUCK_IN)
	elif not any and _ducked:
		_ducked = false
		_to_db(NORMAL_DB, DUCK_OUT)

func _to_db(target: float, time: float) -> void:
	if _tween:
		_tween.kill()
	_tween = create_tween()
	_tween.tween_property(self, "volume_db", target, time)

func _on_game_started() -> void:
	if _started:
		return
	_started = true
	_ducked = false
	volume_db = NORMAL_DB
	play()

func _on_game_ended() -> void:
	stop()

func _on_game_lost(_reason) -> void:
	stop()
