--
-- engineManagement
-- Engine management specialization for IVT transmissions
--
-- @author  Templaer
-- @date  12/06/09
--
-- Modifikationen erst nach Rücksprache
-- Do not edit without my permission
--

engineManagement = {};

function engineManagement.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function engineManagement:load(xmlFile)
	self.backupMinRpm = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motor#minRpm"), 1000);	
    self.origMaxRpm = self.motor.maxRpm[3];
	self.input = 0;
end;

function engineManagement:delete()
end;

function engineManagement:mouseEvent(posX, posY, isDown, isUp, button)
end;

function engineManagement:keyEvent(unicode, sym, modifier, isDown)
end;

function engineManagement:update(dt)
    if self.isEntered then
	
        -- Local variables
	    local alpha = 1;
	    local roundPerMinute = self.lastRoundPerMinute*alpha + (1-alpha)*(self.motor.lastMotorRpm-self.motor.minRpm);
        local rpmDiff = math.abs(roundPerMinute - ((self.origMaxRpm * 0.9) * 100));
		local maxRpm = self.motor:getMaxRpm();
		local rpmSpeedDiff = math.abs(maxRpm - self.motor.lastMotorRpm);
		
	    -- Define input
    	self.input = InputBinding.getAnalogInputAxis(InputBinding.AXIS_FORWARD);
	    if InputBinding.isAxisZero(self.input) then
	    	self.input = InputBinding.getDigitalInputAxis(InputBinding.AXIS_FORWARD);
	    end;
        
		if self.motor.speedLevel ~= 0 and self.cruiseControl then
		    self.input = 1;
		end;
		
		if not self.handThrottleEnabled or self.handThrottleEnabled == nil then -- Check if hand throttle is disabled	
			-- Lower and raise minRpm with a 100 RPM margin
			if math.abs(self.input) > 0.9 then -- Check for input
				if rpmSpeedDiff > (self.origMaxRpm * 0.2) and not self.lowerRpm then
					if roundPerMinute < ((self.origMaxRpm * 100) - 50) then
						self.motor.minRpm = self.motor.minRpm - (rpmDiff / 6000);
					end;
				end;
			end;
			
			if math.abs(self.input) > 0 then
				if rpmSpeedDiff < (1/6.5) * maxRpm or self.lowerRpm then
					if self.motor.minRpm < (maxRpm / 2.35) then
						self.motor.minRpm = self.motor.minRpm + (rpmDiff / 6000);
					end;
				end;
			end;
				
			if self.input == 0 then
			    self.motor.minRpm = self.backupMinRpm; -- Restore backup minRpm
		    end;
		end;
	end;
end;

function engineManagement:stopMotor()
    self.motor.minRpm = self.backupMinRpm;    
end;
	
function engineManagement:onLeave()
    self.motor.mionRpm = self.backupMinRpm;
end;

function engineManagement:draw()
end;
