--[[

	SpeedLimited

	@author:	Robert Hostens
	@date:		2013/05/27
	@version:	v1.0
	@history:	v1.0	- Initial Implementation

	@notes:		Trailers don't have/obey a speed limit property.  We make them do so.
				the code for this was taken from cultivator.lua as shipped from Giants (patch 1.4)
								
	- Example XML -
	<maxSpeedLevel value="2"/>
	
	free for non-commerical usage, for "Farming Simulator 2013" only.

]]


SpeedLimited = {};

function SpeedLimited.prerequisitesPresent(specializations)
	return true;
end;

function SpeedLimited:load(xmlFile)
	self.speedViolationMaxTime = 2500;
	self.speedViolationTimer = self.speedViolationMaxTime;
	self.maxSpeedLevel = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.maxSpeedLevel#value"), 2);
end;

function SpeedLimited:delete()
	-- Do Nothing
end;

function SpeedLimited:mouseEvent(posX, posY, isDown, isUp, button)
	-- Do Nothing
end;

function SpeedLimited:keyEvent(unicode, sym, modifier, isDown)
	-- Do Nothing
end;

function SpeedLimited:update(dt)
	if self:getIsActive() then
		local speedLimit = 20;
		if self.maxSpeedLevel == 2 then
			speedLimit = 30;
		elseif self.maxSpeedLevel == 3 then
			speedLimit = 100;
		end;
		        		
		if self:doCheckSpeedLimit() and self.lastSpeed * 3600 > speedLimit then
			self.speedViolationTimer = self.speedViolationTimer - dt;
			
			if self.isServer then
				if self.speedViolationTimer < 0 then
					if self.attacherVehicle ~= nil then
						self.attacherVehicle:detachImplementByObject(self);
					end;
				end;
			end;
		else
			self.speedViolationTimer = self.speedViolationMaxTime;
		end;
	end;
end;

function SpeedLimited:draw()
	if math.abs(self.speedViolationTimer - self.speedViolationMaxTime) > 2 then
		local buttonName = InputBinding.SPEED_LEVEL1;
		
		if self.maxSpeedLevel == 2 then
			buttonName = InputBinding.SPEED_LEVEL2;
		elseif self.maxSpeedLevel == 3 then
			buttonName = InputBinding.SPEED_LEVEL3;
		end;
		
		g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast").."\n"..string.format(g_i18n:getText("Cruise_control_levelN"), tostring(self.maxSpeedLevel)), 0.07+0.022, 0.019+0.029);
	end;
end;

function SpeedLimited:onActivate()
	-- Do Nothing
end;

function SpeedLimited:onDeactivate()
	self.speedViolationTimer = self.speedViolationMaxTime;
end;