local modName = g_currentModName

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

SteeringAxleNodes = {}

function SteeringAxleNodes.prerequisitesPresent(specializations)
	return SpecializationUtil.hasSpecialization(Attachable, specializations)
end

function SteeringAxleNodes.registerOverwrittenFunctions(vehicleType)
end

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

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

	while true do
		local baseKey = string.format("vehicle.attachable.steeringAxleNodes.steeringAxleNode(%d)", i)

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

		local entry = {
			node = I3DUtil.indexToObject(self.components, getXMLString(self.xmlFile, baseKey .. "#node"), self.i3dMappings),
			offset = math.rad(getXMLFloat(self.xmlFile, baseKey .. "#offset") or 0),
			scale = getXMLFloat(self.xmlFile, baseKey .. "#scale") or 1,
			minFoldLimit = getXMLFloat(self.xmlFile, baseKey .. "#minFoldLimit") or 0,
			maxFoldLimit = getXMLFloat(self.xmlFile, baseKey .. "#maxFoldLimit") or 1
		}

		table.insert(spec.steeringAxleNodes, entry)

		i = i + 1
	end
end
	
function SteeringAxleNodes:onUpdate(dt, isActiveForInput, isActiveForInputIgnoreSelection, isSelected)
	local specAttachable = self.spec_attachable

	if specAttachable.updateSteeringAxleAngle and self:getLastSpeed() > 0.1 then
		local spec = getSpecTable(self)

		for i = 1, #spec.steeringAxleNodes do
			local steeringAxleNode = spec.steeringAxleNodes[i]
			local allowUpdate = true

			if self.getFoldAnimTime ~= nil then
				local time = self:getFoldAnimTime()

				if time < steeringAxleNode.minFoldLimit or steeringAxleNode.maxFoldLimit < time then
					allowUpdate = false
				end
			end

			if allowUpdate then
				setRotation(steeringAxleNode.node, 0, steeringAxleNode.offset + specAttachable.steeringAxleAngle * steeringAxleNode.scale, 0)

				if self.setMovingToolDirty ~= nil then
					self:setMovingToolDirty(steeringAxleNode.node)
				end
			end
		end
	end
end