-- 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 convertProperty(property, value)
	if property == "MaxSpeed" or property == "ReverseSpeed" then
		-- convert to studs/sec
		return value / mphConversion
	end

	return value
end

local changedAttributesConnection = nil
local function updateFromConfiguration()
	local obj = script.Parent.Parent

	for property, value in pairs(VehicleParameters) do
		local configProp = obj:GetAttribute(property)

		if configProp then
			VehicleParameters[property] = convertProperty(property, configProp)
		end
	end

	-- Handle dynamic changes
	changedAttributesConnection = obj.AttributeChanged:Connect(function(property)
		-- Only handle attributes we're interested in
		if VehicleParameters[property] == nil then
			return
		end

		local value = obj:GetAttribute(property)
		VehicleParameters[property] = convertProperty(property, value)

		if DoGravityAdjust then
			gravityAdjust()
		end

		if Chassis then
			Chassis.InitializeDrivingValues() -- reinitialize chassis so that changes are reflected in the rig
		end
	end)
end

updateFromConfiguration()

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
