class_name BallSFX extends Node3D
## Controller for ball sound effects.

const BASE_VOLUME := -36.0
const MAX_VOLUME := 3.0
const VELOCITY_ATTENUATION_SCALE := 400.0

@onready var parent: GameBall = $".."

@onready var grass_sfx_player: AudioStreamPlayer3D = %GrassSFXPlayer
@onready var concrete_sfx_player: AudioStreamPlayer3D = %ConcreteSFXPlayer
@onready var sand_sfx_player: AudioStreamPlayer3D = %SandSFXPlayer
@onready var splash_sfx_player: AudioStreamPlayer3D = %SplashSFXPlayer


func _force_attenuated_volume() -> float:
	# Attenuate volume based on impact force
	return lerpf(
		BASE_VOLUME,
		MAX_VOLUME,
		clampf(parent.linear_velocity.length_squared() / VELOCITY_ATTENUATION_SCALE, 0, 1)
	)


func _play(player: AudioStreamPlayer3D) -> void:
	player.volume_db = _force_attenuated_volume()
	print("PLAYING: ", player, "... VOLUME: ", player.volume_db)
	player.play()


func play_sfx(terrain: Terrain.Type) -> void:
	match terrain:
		Terrain.Type.ROUGH, Terrain.Type.GREEN, Terrain.Type.FAIRWAY:
			_play(grass_sfx_player)
		Terrain.Type.CONCRETE, Terrain.Type.ROCK:
			_play(concrete_sfx_player)
		Terrain.Type.SAND:
			_play(sand_sfx_player)


func play_splash() -> void:
	_play(splash_sfx_player)
