--
-- TowBall
-- Specialization for TowBall functionality
--
-- Modschmiede / LS-Modsource
-- @author  Manuel Leithner
-- @date  25/12/09
--

TowBall = {};

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

function TowBall:load(xmlFile)

	local towBall = getXMLString(xmlFile, "vehicle.towBall#file");
	if towBall ~= nil then
		towBall = Utils.getFilename(towBall, self.baseDirectory);
		self.towBall = towBall;
	else
		print("No towBall path available");
	end;	

	self.attacherJointString = getXMLString(xmlFile, "vehicle.towBall#attacherPoint");
	self.leftFixPointString = getXMLString(xmlFile, "vehicle.towBall#leftFixPoint");
	self.rightFixPointString = getXMLString(xmlFile, "vehicle.towBall#rightFixPoint");	
	
	self.attacherPoint = nil;
	self.leftFixPoint = nil;
	self.rightFixPoint = nil;
	self.loadedTowBall = nil;
	
	self.vehicleJoint = nil;
	self.jointSearch = false;
end;

function TowBall:delete()
end;

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

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

function TowBall:update(dt)		
	
	if self.jointSearch then
		for k,v in pairs(self.attacherVehicle.attachedImplements) do
			if v.object == self then
				local joint = self.attacherVehicle.attacherJoints[v.jointDescIndex];
				self.vehicleJoint = joint;	
				
				-- load,link i3d-File
				local i3dTowBall = loadI3DFile(self.towBall);
				i3dTowBall = getChildAt(i3dTowBall,0);
				if i3dTowBall ~= 0 then
					self.attacherPoint = Utils.indexToObject(i3dTowBall, self.attacherJointString);
					self.leftFixPoint = Utils.indexToObject(i3dTowBall, self.leftFixPointString);
					self.rightFixPoint = Utils.indexToObject(i3dTowBall, self.rightFixPointString);				
					self.loadedTowBall = i3dTowBall;
					link(joint.jointTransform, i3dTowBall);
				end;
				
				setJointFrame(joint.jointIndex, 0, self.attacherPoint);
			end;
		end;
		self.jointSearch = false;
	end;	
end;

function TowBall:draw()
end;


function TowBall:onAttach(attacherVehicle)
	self.jointSearch = true;
end;

function TowBall:onDetach()	

	if self.loadedTowBall ~= nil then
		
		unlink(self.loadedTowBall);
		delete(self.loadedTowBall);
		self.attacherPoint = nil;
		self.leftFixPoint = nil;
		self.rightFixPoint = nil;				
		self.loadedTowBall = nil;
	end;
	self.vehicleJoint = nil;
end;
