--
-- ESLimiter v2.1
-- Specialization for ESLimiter
--
-- SFM-Modding
-- @author	Manuel Leithner
-- @date:		29/08/10
--
-- @edited by	Calamarain (Jonathan McComb)
-- @date:		30/06/2012
--
-- @version:	v2.1
-- @history:	v1.0 - initial implementation
--				v2.0 - convert to LS2011 and some bugfixes
--				v2.1 - Add current engine RPM display
--				v2.1 - Reduce lowest limit to allow for creep in lowest gear at engine idle
--				v2.1 - Reduce change step from 1% to 0.25% for finer control of speed


ESLimiter = {};
function ESLimiter.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function ESLimiter:load(xmlFile)

	self.ESLimiter = {};
	self.ESLimiter.xPos = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.ESLimiter#posX"), 0.7543);
	self.ESLimiter.yPos = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.ESLimiter#posY"), 0.1715);
	self.RPM = {};
	loop = 1;
	-- Raise self.RPMCount if the display updates too fast.
	self.RPMCount = 7;
	loop = self.RPMCount;
	self.RPM.xPos = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.RPM#posX"), 0.7543);
	self.RPM.yPos = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.RPM#posY"), 0.2155);
	self.ESLimiter.maxRPM = {};
	self.ESLimiter.percentage = {};
	rpmDisplay = 0;
	prevRpm = {};
	for i=1,self.RPMCount do
		prevRpm[1] = 0;
	end;
	for k,v in pairs(self.motor.maxRpm) do
		self.ESLimiter.maxRPM[k] = self.motor.maxRpm[3];
		local percentage = string.format("%d",(self.motor.maxRpm[k]* 100 / self.motor.maxRpm[3]));
		self.ESLimiter.percentage[k] = tonumber(percentage); -- percentage
	end;

	self.eslOverlay = Overlay:new("hudESLOverlay", Utils.getFilename("textures/ESLimiter_hud.png", self.baseDirectory), self.ESLimiter.xPos, self.ESLimiter.yPos, 0.2371, 0.039525);
	self.RPMOverlay = Overlay:new("hudESLOverlay", Utils.getFilename("textures/ESLimiter_hud.png", self.baseDirectory), self.RPM.xPos, self.RPM.yPos, 0.2371, 0.039525);
end;

function ESLimiter:delete()
end;

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

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

function ESLimiter:update(dt)
	if self:getIsActiveForInput() then
		local currentLevel = self.motor.speedLevel;
		if self.movingDirection < 0 then
			currentLevel = 1;
		end;

		if currentLevel ~= 0 then
			local percentage = self.ESLimiter.percentage;
			local currentRPM = self.ESLimiter.maxRPM;
			if InputBinding.isPressed(InputBinding.ESLimiter_PLUS) and percentage[currentLevel] < 100 then
				percentage[currentLevel] = percentage[currentLevel] + 0.25;
			elseif InputBinding.isPressed(InputBinding.ESLimiter_MINUS) and percentage[currentLevel] > 1.75 then
				percentage[currentLevel] = percentage[currentLevel] - 0.25;
			end;
			if self.movingDirection > 0 then
				self.motor.maxRpm[currentLevel] = tonumber(string.format("%d",(percentage[currentLevel] * currentRPM[currentLevel] / 100)));
			else
				self.motor.maxRpm[3] = tonumber(string.format("%d",(percentage[currentLevel] * currentRPM[currentLevel] / 100)));
			end;
		else
			self.motor.maxRpm[3] = self.ESLimiter.maxRPM[3];
		end;
	end;
end;

function ESLimiter:draw()
	local currentLevel = self.motor.speedLevel;
	local text = "Deactivated";
	if self.movingDirection < 0 then
		currentLevel = 1;
	end;
	if currentLevel ~= 0 then
		local percentage = tonumber(string.format("%d", self.ESLimiter.percentage[currentLevel]));
		if percentage < 100 then
			percentage = " " .. percentage;
		end;
		text = g_i18n:getText("ESLimiter_level") .. currentLevel .. ":" .. percentage .. "% ";	
	end;
	-- Display ES Limit Info
	self.eslOverlay:render();
	setTextBold(true);
	setTextAlignment(RenderText.ALIGN_LEFT);
	renderText(self.ESLimiter.xPos + 0.13, self.ESLimiter.yPos + 0.0085, 0.02, text);

	-- Get Current RPM & format it for display
	-- Update move previous values 1 step along the array
	for i=1,self.RPMCount-1 do
		prevRpm[i+1] = prevRpm[i];
	end;
	
	-- Add the latest RPM value to the array
	prevRpm[1] = self.motor.lastMotorRpm;
	local rpmsum = 0;
	local rpmAvg = 0;
	-- Only Calculate & Update the displayed RPM every self.RPMCount interations
	if loop == self.RPMCount then
		-- Average the values in the array
		for i=1,self.RPMCount do
			rpmsum = rpmsum + prevRpm[i];
		end
		local rpmAvg = rpmsum / self.RPMCount;
		rpmDisplay = rpmAvg;
	end;
	loop = loop - 1;
	if loop == 0 then
		loop = self.RPMCount;
	end;
	-- Format the info for display on the HUD
	local rpmtext = g_i18n:getText("RPM_HUD")  .. string.format("%d", rpmDisplay);
	
	-- Display Current RPM Info
	self.RPMOverlay:render();
	setTextBold(true);
	setTextAlignment(RenderText.ALIGN_LEFT);
	renderText(self.RPM.xPos + 0.13, self.RPM.yPos + 0.0085, 0.02, rpmtext);
	
	-- Display RPM Help Text
	g_currentMission:addExtraPrintText(string.format(g_i18n:getText("ESLimiter_controls"), self.typeDesc) .. " " .. InputBinding.getKeyNamesOfDigitalAction(InputBinding.ESLimiter_PLUS) .. " & " .. InputBinding.getKeyNamesOfDigitalAction(InputBinding.ESLimiter_MINUS));
end;


function ESLimiter:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	if not resetVehicles then
		local valueStr = getXMLString(xmlFile, key.."#limiterValues");		
		if valueStr ~= nil then
			local found = string.find(valueStr, ";");
			local index = 1;
			while found ~= nil do
				local value = string.sub(valueStr, 0, found-1);
				valueStr = string.sub(valueStr, found+1);
				found = string.find(valueStr, ";");
				self.ESLimiter.percentage[index] = tonumber(value);
				if found == nil then
					self.ESLimiter.percentage[index+1] = tonumber(valueStr);
				end;
				index = index + 1;	
			end;
		end;
	end; 

    return BaseMission.VEHICLE_LOAD_OK;
end;

function ESLimiter:getSaveAttributesAndNodes(nodeIdent)
	local values = "";	
	for k,v in pairs(self.ESLimiter.percentage) do
		if k ~= 1 then
			values = values .. ";";
		end;
		values = values .. string.format("%d", v);
	end;
	
    local attributes = 'limiterValues="'.. values .. '"';
    return attributes, nil;
end;