extends AudioStreamPlayer

const MUTE_VOLUME := -80.0

@export var volume_increment := 0.618
@export var base_volume := -14.0
@export var boosted_volume := -2.0

var target_volume := MUTE_VOLUME
var suppressed := false
var boosted := false


func _ready() -> void:
	Game.manager.alert_raised.connect(_on_alert_raised)


func get_target_volume() -> float:
	if suppressed:
		return MUTE_VOLUME
	if boosted:
		return boosted_volume
	return target_volume


## Temporarily suppress ambience
func suppress(time: float = 5.0) -> void:
	suppressed = true
	get_tree().create_timer(time).timeout.connect(_unsuppress)


## Temporarily boost ambience
func boost(time: float = 5.0) -> void:
	boosted = true
	get_tree().create_timer(time).timeout.connect(_unboost)


func _unsuppress() -> void:
	suppressed = false


func _unboost() -> void:
	boosted = false


func _process(delta: float) -> void:
	volume_db = lerpf(volume_db, get_target_volume(), volume_increment * delta)


func _on_player_enters_ship(_body: Node3D) -> void:
	target_volume = MUTE_VOLUME


func _on_player_exits_ship(_body: Node3D) -> void:
	target_volume = base_volume


func _on_alert_raised(new_level: int) -> void:
	if new_level == Game.manager.MAX_ALERT:
		suppress(30)
	else:
		boost(10.0)
