local modName = g_currentModName

local function getSpecTable(self)
	return self["spec_" .. modName .. ".speedLimitModifier"]
end

SpeedLimitModifier = {}

function SpeedLimitModifier.prerequisitesPresent(specializations)
	return true
end

function SpeedLimitModifier.registerFunctions(vehicleType)
	return true
end

function SpeedLimitModifier.registerOverwrittenFunctions(vehicleType)
	return true
end

function SpeedLimitModifier.registerEventListeners(vehicleType)
	SpecializationUtil.registerEventListener(vehicleType, "onLoad", SpeedLimitModifier)
end

function SpeedLimitModifier:onLoad(savegame)
	local spec = getSpecTable(self)
	spec.speedLimitModifier = {}
	local i = 0

	while true do
		local baseKey = string.format("vehicle.powerConsumer.speedLimitModifier(%d)", i)

		if not hasXMLProperty(self.xmlFile, baseKey) then
			break
		end

		local entry = {
			offset = getXMLFloat(self.xmlFile, baseKey .. "#offset")
		}

		if entry.offset ~= nil then
			entry.minPowerKw = (getXMLFloat(self.xmlFile, baseKey .. "#minPowerHp") or 0) * 0.735499
			entry.maxPowerKw = (getXMLFloat(self.xmlFile, baseKey .. "#maxPowerHp") or 0) * 0.735499

			table.insert(spec.speedLimitModifier, entry)
		end

		i = i + 1
	end
end

local oldGetSpeedLimit = Vehicle.getSpeedLimit

function Vehicle:getSpeedLimit(onlyIfWorking)
	local speedLimit, doCheckSpeedLimit = oldGetSpeedLimit(self, onlyIfWorking)
	local spec = getSpecTable(self)

	if spec ~= nil and spec.speedLimitModifier ~= nil and speedLimit ~= math.huge then
		local rootVehicle = self:getRootVehicle()

		if rootVehicle ~= nil and rootVehicle.getMotor ~= nil then
			local rootMotor = rootVehicle:getMotor()
			local peakMotorPower = rootMotor.peakMotorPower

			for i = 1, #spec.speedLimitModifier do
				local modifier = spec.speedLimitModifier[i]

				if modifier.minPowerKw <= peakMotorPower and peakMotorPower <= modifier.maxPowerKw then
					return speedLimit + modifier.offset, doCheckSpeedLimit
				end
			end
		end
	end

	return speedLimit, doCheckSpeedLimit
end