--
-- @author  Geri-G
-- @date  13/07/10
--
-- Copyright (C) Geri-G
--


autoAttacher = {};

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

function autoAttacher:load(xmlFile)
	self.searchObjects = autoAttacher.searchObjects;
	self.attachobjects = autoAttacher.attachobjects;
	self.detachobjects = autoAttacher.detachobjects;
	self.OrientJoint = autoAttacher.OrientJoint;
	self.setObjectAttachingState = autoAttacher.setObjectAttachingState;
	self.isObjectInRange = autoAttacher.isObjectInRange;
	self.place = {};
	local i=0;
	while true do
		local basename = string.format("vehicle.castPoints.castPoint(%d)",i);
		local place = {};
		place.node1 = Utils.indexToObject(self.components, getXMLString(xmlFile,basename.."#frontRight"));

		if place.node1 == nil then
			break;
		end;
		place.node2 = Utils.indexToObject(self.components, getXMLString(xmlFile,basename.."#backLeft"));
		place.attacherNode = Utils.indexToObject(self.components, Utils.getNoNil(getXMLString(xmlFile,basename.."#attacherNode"),"0>"));
		place.highOffset = Utils.getNoNil(getXMLFloat(xmlFile,basename.."#highOffset"),4);
		table.insert(self.place,place);
		i=i+1;
	end;
	self.allowVehicleAttachment = getXMLBool(xmlFile,"vehicle.castPoints#allowVehicleAttachment");
	self.allowAttachment = true;
	self.Attachedobjects = {};
	self.objectsAttached = false;	
	self.oldRotComp3 = {getWorldRotation(self.components[3].node)};
end;

function autoAttacher:readStream(streamId, connection)	
end;
function autoAttacher:writeStream(streamId, connection)
end;
function autoAttacher:keyEvent(unicode, sym, modifier, isDown)
end;

function autoAttacher:draw()	     
end;

function autoAttacher:update(dt)
	local x,y,z = getWorldRotation(self.components[3].node);
	if x ~= self.oldRotComp3[1] or y ~= self.oldRotComp3[2] or z ~= self.oldRotComp3[3] then
		self.oldRotComp3 = {x,y,z};
	end;
end;

function autoAttacher:updateTick(dt)
	if self:getIsActive() and self.isServer then
		if self.allowAttachment then
			if self.objectsAttached == false then
				self:setObjectAttachingState(false);
			end;
		else
			if self.objectsAttached == true then
				self:setObjectAttachingState(true);
			end;
		end;
	end;
end;

function autoAttacher:isObjectInRange(place,object)
	local Xmax, Ymax, Zmax = getWorldTranslation(place.node1);
		  Xmax, Ymax, Zmax = worldToLocal(place.attacherNode,Xmax, Ymax, Zmax);		  
	local Xmin, Ymin, Zmin = getWorldTranslation(place.node2);	
		  Xmin, Ymin, Zmin = worldToLocal(place.attacherNode,Xmin, Ymin, Zmin);	
	local Xt, Yt, Zt = getWorldTranslation(object);
		  Xt, Yt, Zt = worldToLocal(place.attacherNode,Xt, Yt, Zt);		
	if (Xt < math.max(Xmax,Xmin) and Xt > math.min(Xmax,Xmin)) and (Zt < math.max(Zmax,Zmin) and Zt > math.min(Zmax,Zmin)) and (Yt<= ((Ymax+Ymin)/2)+place.highOffset and Yt>= (Ymax+Ymin)/2) then
		return true;
	else
		return false;
	end;
end;

function autoAttacher:searchObjects()
	for index,item in pairs(g_currentMission.itemsToSave) do
		if item.item:isa(Bale) then 
			if item.item.isAttached == nil then
				for k,v in pairs(self.place) do
					local isInRange = self:isObjectInRange(v,item.item.nodeId);			
					local is1stAttached = false;
					if isInRange then
						is1stAttached = self:attachobjects(v,item.item.nodeId,item.item);
					end;
					if is1stAttached then
						self.objectsAttached = true;
					end;
				end;
			end;
		end;
	end;
	if self.allowVehicleAttachment == true then
		for k,v in pairs(g_currentMission.vehicles) do
			if v ~= self and v ~= self.attacherVehicle then
				local is1stAttached = false;
				for index,components in pairs(v.components) do		
					for k1,v1 in pairs(self.place) do
						local isInRange = self:isObjectInRange(v1,components.node);	
						if isInRange then	
							is1stAttached = self:attachobjects(v1,components.node);
						end;
					end;
				end;
				if is1stAttached then
					self.objectsAttached = true;
				end;
			end;
		end;
	end;
end;

function autoAttacher:setObjectAttachingState(isCoupling,noEventSend)
	if not noEventSend and self.objectsAttached == isCoupling and not self.allowAttachment then
	end;
	if isCoupling then
		self:detachobjects();	
	elseif not isCoupling and not self.objectsAttached then
		self:searchObjects();
	end;
end;

function autoAttacher:OrientJoint(Source, Target)	
	local xw, yw, zw = getWorldTranslation(Source);		
	local x,y,z = worldToLocal(getParent(Target), xw, yw, zw);	
	setTranslation(Target, x,y,z);			
	local zX, zY, zZ = localDirectionToWorld(Source, 0,0,1);
	local zX, zY, zZ = worldDirectionToLocal(getParent(Target), zX, zY, zZ);
	local yX, yY, yZ = localDirectionToWorld(Source, 0,1,0);
	local yX, yY, yZ = worldDirectionToLocal(getParent(Target), yX, yY, yZ);
	setDirection(Target, zX, zY, zZ, yX, yY, yZ);
	return false;
end;

function autoAttacher:attachobjects(place,object,baleT)
	local attachedobject = {};
	attachedobject.object = object;
	if self.isServer then
		attachedobject.AT = createTransformGroup("AT");
		link(place.attacherNode,attachedobject.AT);		
		attachedobject.objectMass = getMass(object);
		setMass(object,attachedobject.objectMass*0.1);		
		self:OrientJoint(object,attachedobject.AT);
		local constr = JointConstructor:new();					
		constr:setActors(place.attacherNode, object);
		constr:setJointTransforms(attachedobject.AT,  object);
		for i=1, 3 do
			constr:setTranslationLimit(i-1, true, 0, 0);
			constr:setRotationLimit(i-1,0,0);
		end;
		attachedobject.JointIndex = constr:finalize();		
		if baleT ~= nil then
			attachedobject.baleT = baleT;
			baleT.isAttached = true;
		end;
	end;
	table.insert(self.Attachedobjects, attachedobject);
	return true;
end;

function autoAttacher:detachobjects()
	if self.isServer then
		for k,v in pairs(self.Attachedobjects) do
			removeJoint(v.JointIndex);
			delete(v.AT);
			v.JointIndex = nil;
			setMass(v.object,v.objectMass);
			if v.baleT ~= nil then
				v.baleT.isAttached = nil;
			end;
		end;
	end;	
	self.Attachedobjects = nil;
	self.Attachedobjects = {};
	self.objectsAttached = false;
end;

function autoAttacher:onAttach(attacherVehicle)
	if self.isServer then
		self:setObjectAttachingState(false);
	end;
end;
function autoAttacher:onDetach()
	if self.isServer then
		self:setObjectAttachingState(true);
	end;
end;
function autoAttacher:onActivate()
	if self.isServer then
		self:setObjectAttachingState(false);
	end;
end;
function autoAttacher:onDeactivate()
	if self.isServer then
		self:setObjectAttachingState(true);
	end;
end;
function autoAttacher:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	if not resetVehicles then
	end;
    return BaseMission.VEHICLE_LOAD_OK;
end;
function autoAttacher:getSaveAttributesAndNodes(nodeIdent)
    local attributes = nil;
    local node = nil;
    return attributes, node;
end;
function autoAttacher:delete()
end;
function autoAttacher:mouseEvent(posX, posY, isDown, isUp, button)
end;


