extends Node

export var f1_node: NodePath
export var f2_node: NodePath
export var f3_node: NodePath

var f1: AudioStreamPlayer3D
var f2: AudioStreamPlayer3D
var f3: AudioStreamPlayer3D
var rev_min: float = 1
var rev_multiplier: float = 3 # Higher values result in higher revs.
var amplification_high: AudioEffectAmplify
var amplification_dominant: AudioEffectAmplify
var amplification_low: AudioEffectAmplify
var time_start: int
var time_now: int
var time_diff: float

func _ready():
	randomize()
	f1 = get_node(f1_node)
	f2 = get_node(f2_node)
	f3 = get_node(f3_node)
	f1.play()
	f2.play()
	f3.play()
	var index_high = AudioServer.get_bus_index("High")
	amplification_high = AudioServer.get_bus_effect(index_high, 0)
	var index_dominant = AudioServer.get_bus_index("Dominant")
	amplification_dominant = AudioServer.get_bus_effect(index_dominant, 0)
	var index_low = AudioServer.get_bus_index("Low")
	amplification_low = AudioServer.get_bus_effect(index_low, 0)
	time_start = OS.get_ticks_msec()

func _on_Monteri_update_motor_sound(vehicle_controller):
	var speed: float = vehicle_controller.linear_velocity.length()
	var pitch = rev_min + rev_multiplier * speed / vehicle_controller.vmax
	var acceleration: float = vehicle_controller.acceleration_measurement
	var random: float = randf()
	var v_cut_off = vehicle_controller.get_vmax() - 1.2
	var acceleration_force_relative = vehicle_controller.get_acceleration_force_relative()
	var cut_off: bool
	var force_ratio: float = vehicle_controller.get_acceleration_force_relative()
	var db_high: float = 6 * force_ratio
	time_now = OS.get_ticks_msec()
	if time_now >= time_start + 110:
		time_diff = 0.5 * (time_now - time_start)
		time_start = time_now
	if time_now >= time_start + time_diff:
		cut_off = true
	else:
		cut_off = false
	f1.pitch_scale = pitch
	f2.pitch_scale = pitch
	f3.pitch_scale = pitch
	if speed > v_cut_off && acceleration_force_relative > 0:
		if !cut_off:
			amplification_high.volume_db = db_high
			amplification_dominant.volume_db = db_high
			amplification_low.volume_db = db_high
		else:
			amplification_high.volume_db = -20
			amplification_dominant.volume_db = 0
			amplification_low.volume_db = 0
	else: if speed < 1:
		if random < 0.5:
			amplification_high.volume_db = 0
			amplification_dominant.volume_db = 0
			amplification_low.volume_db = 0
		else:
			amplification_high.volume_db = -20
			amplification_dominant.volume_db = 0
			amplification_low.volume_db = 0
	else:
		if acceleration > 0:
			amplification_high.volume_db = 0
			amplification_dominant.volume_db = db_high
			amplification_low.volume_db = db_high
		else:
			amplification_high.volume_db = -20
			amplification_dominant.volume_db = -3
			amplification_low.volume_db = 6


