--
-- Name: Steerable Update
-- Description: Updates to the Steerable specialization to implement the Inversore reverser
-- Version: 2.0
-- Author: Stefan Geiger (Edit by Templaer)
-- Date: 10/04/2011
--

InversoreUpdate = {};

-- Extended original function --
function InversoreUpdate.updateVehiclePhysics(self, axisForward, axisForwardIsAnalog, axisSide, axisSideIsAnalog, dt)
	local acceleration = 0;
	if self.isMotorStarted and self.motorStartTime <= self.time then
		acceleration = -axisForward;
		if math.abs(acceleration) > 0.8 then
			if self.motor.speedLevel ~= 0 then
				self.lastAcceleration = self.lastAcceleration*0.5;
			end;
			self.motor:setSpeedLevel(0, true)
		end;
		if self.motor.speedLevel ~= 0 then
			acceleration = self.motor.accelerations[self.motor.speedLevel];
		end;
	end;
	if self.fuelFillLevel == 0 then
		acceleration = 0;
	end;

	-- Check if the Inversore is enabled --
	if not self.InversoreOverride and self.InversoreEnabled then
		if acceleration > 0 then
			acceleration = acceleration * self.InversoreDirection;
		elseif self.movingDirection <= 0 then
			acceleration = 0;
		end;
	end;
	
	acceleration = Steerable.calculateRealAcceleration(self, acceleration, dt);
   
   local inputAxisX = axisSide;
   if axisSideIsAnalog then
	   local targetRotatedTime = 0;
	   if inputAxisX < 0 then
		   -- 0 to maxRotTime
		   targetRotatedTime = math.min(-self.maxRotTime*inputAxisX, self.maxRotTime);
	   else
		   -- 0 to minRotTime
		   targetRotatedTime = math.max(self.minRotTime*inputAxisX, self.minRotTime);
	   end;
	   local maxTime = self.maxRotatedTimeSpeed*dt;
	   if math.abs(targetRotatedTime-self.rotatedTime) > maxTime then
		   if targetRotatedTime > self.rotatedTime then
			   self.rotatedTime = self.rotatedTime + maxTime;
		   else
			   self.rotatedTime = self.rotatedTime - maxTime;
		   end;
	   else
		   self.rotatedTime = targetRotatedTime;
	   end;
   else
	   local rotScale = math.min(1.0/(self.lastSpeed*self.speedRotScale+self.speedRotScaleOffset), 1);
	   if inputAxisX < 0 then
		   self.rotatedTime = math.min(self.rotatedTime - dt/1000*inputAxisX*rotScale, self.maxRotTime);
	   elseif inputAxisX > 0 then
		   self.rotatedTime = math.max(self.rotatedTime - dt/1000*inputAxisX*rotScale, self.minRotTime);
	   else
		   if self.autoRotateBackSpeed ~= 0 then
			   if self.rotatedTime > 0 then
				   self.rotatedTime = math.max(self.rotatedTime - dt/1000*self.autoRotateBackSpeed*rotScale, 0);
			   else
				   self.rotatedTime = math.min(self.rotatedTime + dt/1000*self.autoRotateBackSpeed*rotScale, 0);
			   end;
		   end;
	   end;
   end;

   if self.firstTimeRun then
	   WheelsUtil.updateWheelsPhysics(self, dt, self.lastSpeed, acceleration, false, self.requiredDriveMode)
   end;
end;

-- Overwrite the original function --
Steerable.updateVehiclePhysics = InversoreUpdate.updateVehiclePhysics;