-- Script by @poc@lypse.

Pince900c = {};

function Pince900c.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Trailer, specializations);
end;

function Pince900c:load(xmlFile)
self.findloadTriggerRaycastCallback = Pince900c.findloadTriggerRaycastCallback;
self.loadRaycastNode = self.rootNode;
	self.fallOut = true;
	self.fallOut2 = false;
	self.implementFallOut = true;
	self.isShovel = true;
        self.open = false;
end;

function Pince900c:delete()
end;

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

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

function Pince900c:update(dt)
	
	
	self.fallOut2 = false;
  if self.attacherVehicle ~= nil then
		self.fallOut2 = false;
		local x,y,z = worldDirectionToLocal(self.steeringAxleNode, localDirectionToWorld(self.attacherVehicle.steeringAxleNode, 0, 1, 0));
		if z < 0 then
			self.fallOut = true;
		else
			self.fallOut = true;
		end;
		self.tiltangle = z;
	end;
	if self.fallOut and self.implementFallOut then		
		local nearestDistance = 7;
		local px, py, pz = getWorldTranslation(self.tipReferencePoint);
		for i=1, table.getn(g_currentMission.attachables) do
      local vx, vy, vz = getWorldTranslation(g_currentMission.attachables[i].rootNode);
			local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
			if distance < nearestDistance then
				local attachable = g_currentMission.attachables[i];		
				if attachable.fillTypes ~= nil and attachable.setFillLevel ~= nil and attachable.fillLevel ~= nil and attachable ~= self then
					if self.currentFillType == attachable.currentFillType or attachable.currentFillType == FruitUtil.FRUITTYPE_UNKNOWN then
						if attachable.fillLevel < attachable.capacity  and self.fillLevel > 1 and self.foldMoveDirection > 0.1 then							
							local deltaLevel = (self.capacity/200)*(dt*0.1)						
							local fillDelta = math.min(deltaLevel, self.fillLevel)
							self:setFillLevel(self.fillLevel - fillDelta, self.currentFillType);
							attachable:setFillLevel(attachable.fillLevel + fillDelta, self.currentFillType);
							self.fallOut2 = self.fillLevel>0 and fillDelta>0;						
						end; 
					end;
				end;
			end;
		end;		
	end;
	Utils.setEmittingState(self.dischargeParticleSystems[self.currentFillType], self.fallOut2);
end;

function Pince900c:draw()
end;

function Pince900c:onDetach()
    if self.deactivateOnDetach then
        Pince900c.onDeactivate(self);
    end;
end;

function Pince900c:onDeactivate()
    self.fallOut = false;
end;

function Pince900c:findloadTriggerRaycastCallback(transformId, x, y, z, distance)
	local id = 0;
    if getCollisionMask(transformId) == 8192 then
        id = transformId;
    end;
	self.triggerFound = id;
	return;
end;
