-- Adjust torque and springs based on gravity to keep the car drivable

local function gravityAdjust()
	local defaultGravity = 196.2
	local actualGravity = Workspace.Gravity
	local gravityChange = actualGravity / defaultGravity
	-- Speed is adjusted so that the height of jumps is preserved
	-- So maxSpeed is scaled proportionally to the sqrt of gravity
	ActualDrivingTorque = VehicleParameters.DrivingTorque * gravityChange
	ActualBrakingTorque = VehicleParameters.BrakingTorque * gravityChange

	ActualStrutSpringStiffnessFront = VehicleParameters.StrutSpringStiffnessFront * gravityChange
	ActualStrutSpringDampingFront = VehicleParameters.StrutSpringDampingFront * math.sqrt( gravityChange )
	ActualStrutSpringStiffnessRear = VehicleParameters.StrutSpringStiffnessRear * gravityChange
	ActualStrutSpringDampingRear = VehicleParameters.StrutSpringDampingRear * math.sqrt( gravityChange )

	ActualTorsionSpringStiffness = VehicleParameters.TorsionSpringStiffness * gravityChange
	ActualTorsionSpringDamping = VehicleParameters.TorsionSpringDamping * math.sqrt( gravityChange )
end

local function updateFromConfiguration()
	for property, value in pairs(VehicleParameters) do
		local configProp = VehicleConfig:FindFirstChild(property)
		if configProp then
			if property == "MaxSpeed" or property == "ReverseSpeed" then
				VehicleParameters[property] = configProp.Value/mphConversion -- convert to studs/sec
			else
				VehicleParameters[property] = configProp.Value
			end
		end
	end
end

local updateEvents
if VehicleConfig then
	updateFromConfiguration()

	updateEvents = {}
	local props = VehicleConfig:GetChildren()
	for i = 1, #props do
		updateEvents[props[i].Name] = props[i].Changed:connect(function(value)
			VehicleParameters[props[i].Name] = value
			if DoGravityAdjust then
				gravityAdjust()
			end
			if Chassis then
				Chassis.InitializeDrivingValues() -- reinitialize chassis so that changes are reflected in the rig
			end
		end)
	end
end

if DoGravityAdjust then
	gravityAdjust()
end

workspace.Changed:Connect(function(prop)
	if prop == "Gravity" then
		if DoGravityAdjust then
			gravityAdjust()
		end
		if Chassis then
			Chassis.InitializeDrivingValues() -- reinitialize chassis so that changes are reflected in the rig
		end
	end
end)

local Motors
local SteeringPrismatic
local RedressMount
