## UltrasoundMachine — displays a continuous heartbeat pulse on the screen.
## Plays looping ambient heartbeat audio when the ultrasound room is active.
class_name UltrasoundMachine extends Node2D

const BEAT_RISE_DURATION: float = 0.12
const BEAT_FALL_DURATION: float = 0.12
const BEAT_INTERVAL: float = 0.60
const BEAT_SCALE_PEAK: Vector2 = Vector2(1.5, 1.5)
const BEAT_SCALE_REST: Vector2 = Vector2(1.0, 1.0)
const _HEARTBEAT_PATH: String = "res://assets/audio/sfx/ultrasound_heartbeat.ogg"

@export var trigger_floor: int = 2
@export var trigger_room: int = 0

var _audio: AudioStreamPlayer


func _ready() -> void:
	_start_heartbeat_loop()
	_setup_audio()
	RoomNavigator.room_changed.connect(_on_room_changed)


func _exit_tree() -> void:
	if RoomNavigator.room_changed.is_connected(_on_room_changed):
		RoomNavigator.room_changed.disconnect(_on_room_changed)


func _setup_audio() -> void:
	_audio = AudioStreamPlayer.new()
	add_child(_audio)
	if AudioServer.get_driver_name() == "Dummy":
		return
	if not ResourceLoader.exists(_HEARTBEAT_PATH):
		return
	var base: AudioStream = load(_HEARTBEAT_PATH) as AudioStream
	if base == null:
		return
	var ogg: AudioStreamOggVorbis = base as AudioStreamOggVorbis
	if ogg == null:
		return
	ogg = ogg.duplicate() as AudioStreamOggVorbis
	ogg.loop = true
	_audio.stream = ogg


func _on_room_changed(floor_index: int, room_index: int) -> void:
	if _audio == null or _audio.stream == null:
		return
	if floor_index == trigger_floor and room_index == trigger_room:
		_audio.play()
	else:
		_audio.stop()


func _start_heartbeat_loop() -> void:
	var dot: Node2D = get_node_or_null("HeartbeatDot") as Node2D
	if dot == null:
		return
	var tween: Tween = create_tween()
	tween.set_loops()
	tween.tween_property(dot, "scale", BEAT_SCALE_PEAK, BEAT_RISE_DURATION)
	tween.tween_property(dot, "scale", BEAT_SCALE_REST, BEAT_FALL_DURATION)
	tween.tween_interval(BEAT_INTERVAL)
