DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`expedition_entering`(vExpeditionFk INT, OUT vExpeditionOutFk INT )
BEGIN
	
	/**
	 * Una expedición llega a la entrada del celuveyor y comunica su ID
	 *
	 * @param vExpeditionFk Identificador de srt.expedition
	 * 
	 * @return vExpeditionOutFk Identificador de srt.expedition
	 * 
	 */
	
	DECLARE vBufferFk INT DEFAULT NULL;
    
	SET vExpeditionOutFk = srt.expedition_check(vExpeditionFk);
  	  
	IF vExpeditionOutFk < 0  THEN 
	
		SELECT IF(vExpeditionOutFk MOD 10 = 0, c.bufferNoLabels, c.bufferTwoLabels) 
			INTO vBufferFk
			FROM srt.config c;
	
	END IF;

	UPDATE srt.expedition e 
		SET e.bufferFk = 0
		WHERE id = vExpeditionOutFk;
	
	UPDATE srt.moving m
		JOIN srt.movingState ms ON ms.description = 'NEW'
		SET m.stateFk = ms.id
		WHERE m.expeditionFk = vExpeditionOutFk;
	
	IF (SELECT isAuto FROM srt.config) THEN 
	
		SELECT b.id INTO vBufferFk 
			FROM srt.buffer b 
				JOIN srt.bufferType bt ON bt.id = b.typeFk 
			WHERE b.isActive
			ORDER BY (bt.typeName = 'STRAPPING') DESC,
					b.hasWorkerWaiting DESC,
					srt.buffer_IsFull(b.id), 
					b.stateFk, 
					b.typeFk,
					b.lastUnloaded,
					b.id DESC
			LIMIT 1;
	
	END IF;
/*
	INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
		VALUES(vExpeditionOutFk, 0, 'ENT');

	INSERT INTO srt.enteringLog(expeditionFk , expeditionOutFk )
		VALUES(vExpeditionFk, vExpeditionOutFk);
*/	
	CALL srt.expedition_relocate(vExpeditionOutFk, vBufferFk);

END$$
DELIMITER ;
