--
-- AnimatedCylinders v1.0
-- Specialization for Animated Cylinders
--
-- @author  	fruktor (Modding-Society)
-- @edited by: 	Milan Lekše (Milan1702976)
-- @date:		17/08/2012
-- @version:	v1.0
--
-- @Usage:
--
--	<AnimatedCylinders>
--		<cylinder girl="0>0|4|0" boy="0>0|4|0|0" ref="0>0|4|0|0|0" target="1>2" />
--	</AnimatedCylinders>
--

AnimatedCylinders = {};

function AnimatedCylinders.prerequisitesPresent(specializations)
    return true
end;

function AnimatedCylinders:load(xmlFile)
	local i=0;
	self.cylinders = {};
	while true do
		local girl = Utils.indexToObject( self.components, getXMLString(xmlFile, string.format("vehicle.AnimatedCylinders.cylinder(%d)#girl",i)) );
		if girl == nil then
			break;
		end;
		local boy = Utils.indexToObject( self.components, getXMLString(xmlFile, string.format("vehicle.AnimatedCylinders.cylinder(%d)#boy",i)) );
		local ref = Utils.indexToObject( self.components, getXMLString(xmlFile, string.format("vehicle.AnimatedCylinders.cylinder(%d)#ref",i)) );
		local target = Utils.indexToObject( self.components, getXMLString(xmlFile, string.format("vehicle.AnimatedCylinders.cylinder(%d)#target",i)) );
		
		local entry = {};
		entry.girl = girl;
		entry.defaultSX, entry.defaultSY, entry.defaultSZ = getScale(girl);
		entry.boy = boy;
		entry.ref = ref;
		entry.target = target;
		local x1, y1, z1 = getWorldTranslation(boy);
		local x2, y2, z2 = getWorldTranslation(ref);
		entry.length2 = Utils.vector3Length(x1-x2, y1-y2, z1-z2);
		
		i=i+1;
		table.insert(self.cylinders, entry);
	end;
end;

function AnimatedCylinders:delete()
end;

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

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

function AnimatedCylinders:readStream(streamId, connection)
end;

function AnimatedCylinders:writeStream(streamId, connection)
end;

function AnimatedCylinders:update(dt)
end;

function AnimatedCylinders:updateTick(dt)
	for i, cylinder in pairs(self.cylinders) do
		setScale(cylinder.girl, cylinder.defaultSX, cylinder.defaultSY, cylinder.defaultSZ)
		local ax, ay, az = getWorldTranslation(cylinder.girl);
		local bx, by, bz = getWorldTranslation(cylinder.target);
		local x, y, z = worldDirectionToLocal(getParent(cylinder.girl), bx-ax, by-ay, bz-az);
		
		local upX, upY, upZ = 0,1,0;
		if math.abs(y) > 0.99*Utils.vector3Length(x, y, z) then
			-- direction and up is parallel
			upY = 0;
			if y > 0 then
				upZ = 1;
			else
				upZ = -1;
			end;
		end;
		
		setDirection(cylinder.girl, x, y, z, upX, upY, upZ);
		local distance = Utils.vector3Length(ax-bx, ay-by, az-bz);
		setTranslation(cylinder.boy, 0, 0, distance - cylinder.length2);			
	end;
end;

function AnimatedCylinders:draw()	
end;

function AnimatedCylinders:onAttach()
end;

function AnimatedCylinders:onDetach()
end;

function AnimatedCylinders:onLeave()
end;

function AnimatedCylinders:onEnter()
end;