--
-- CardanShafts
-- Specialization for animating cardan shafts
--
-- @author    PES 4ever
-- @date      11/07/11
-- @version   1.0
--
-- For support and documentation visit www.modding-society.de
-- Modifications only with my permission
--

CardanShafts = {};

function CardanShafts.prerequisitesPresent(specializations)
	return SpecializationUtil.hasSpecialization(Cylindered, specializations);
end;

function CardanShafts:load(xmlFile)

	-- Cardan shafts
	self.cardanShafts = {};
	local i = 0;
	while true do
		local baseName = string.format("vehicle.cardanShafts.cardanShaft(%d)", i);
		if not hasXMLProperty(xmlFile, baseName) then
			break;
		end;
		
		local node = Utils.indexToObject(self.components, getXMLString(xmlFile, baseName .. "#cardanJoint1"));
		if node ~= nil then
			local entry = {};
			entry.joint1 = node;
			entry.joint2 = Utils.indexToObject(self.components, getXMLString(xmlFile, baseName .. "#cardanJoint2"));
			if entry.joint2 ~= nil then			
				local number = getXMLInt(xmlFile, baseName .. "#movingPartNumber");
				if number ~= nil then
					if number >= 1 or number <= table.getn(self.movingParts) then
						entry.movingPartNumber = number;
						entry.needsUpdate = true;
						entry.ongoingUpdate = Utils.getNoNil(getXMLBool(xmlFile, baseName .. "#ongoingUpdate", false));
						entry.speedFactor = Utils.getNoNil(getXMLFloat(xmlFile, baseName .. "#speedFactor"), 1);
						table.insert(self.cardanShafts, entry);						
					else
						print("Warning: index number of moving part in cardan shaft ".. i+1 .." does not exist in '".. self.configFileName .."'");
					end;
				end;				
			end;
		end;
		
		i = i + 1;
	end;
	
end;

function CardanShafts:delete()
end;

function CardanShafts:readStream(streamId, connection)
end;

function CardanShafts:writeStream(streamId, connection)	
end;

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

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

function CardanShafts:update(dt)
end;

function CardanShafts:updateTick(dt)
	
	if self:getIsActive() and self.isClient then
	
		for _, shaft in pairs(self.cardanShafts) do
	
			if shaft.needsUpdate then
			
				-- Rotate cardan shafts
				local x, y, z = getRotation(self.wheels[1].driveNode);
				setRotation(shaft.joint1, 0 , 0, x * shaft.speedFactor);
				setRotation(shaft.joint2, 0 , 0, x * shaft.speedFactor);
				
				-- Update movingPart
				Cylindered.updateMovingPart(self, self.movingParts[shaft.movingPartNumber]);

				if not shaft.ongoingUpdate then
					shaft.needsUpdate = false;
				end;
				
			end;
		end;
	end;
	
end;

function CardanShafts:draw()
end;