DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`expedition_out`(vBufferFk INT, OUT vTypeFk INT)
proc:BEGIN 
/**
 * Una expedición ha salido de un buffer por el extremo distal
 * Se ignorará en caso de que el buffer esté en modo ACCUMULATION
 *
 * @param vBufferFk Identificador de srt.buffer
 *
 * @return vTypeFk Identificador de srt.bufferType
 */

	DECLARE vMaxPosition INT;
	DECLARE vIsFree BOOL;
	DECLARE vExpeditionFk INT;
	DECLARE vBufferType VARCHAR(15);

	SELECT bt.typeName
		INTO vBufferType
		FROM srt.buffer b 
			JOIN srt.bufferType bt ON bt.id = b.typeFk
		WHERE b.id = vBufferFk;

	IF vBufferType = 'ACCUMULATION' THEN
		LEAVE proc;
	END IF;

	SELECT MAX(e.`position`) INTO vMaxPosition
		FROM srt.expedition e
			WHERE e.bufferFk = vBufferFk;

	SELECT e.id INTO vExpeditionFk
		FROM srt.expedition e
		WHERE e.`position` = vMaxPosition
			AND e.bufferFk = vBufferFk
		LIMIT 1;

	INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
		VALUES(vExpeditionFk, vBufferFk, 'OUT');

	UPDATE srt.expedition e 
		JOIN srt.expeditionState es ON es.description = 'OUT'
		SET e.bufferFk = NULL, 
			e.`position` = NULL,
			e.stateFk = es.id
		WHERE e.id = vExpeditionFk;

	SELECT (COUNT(*) = 0) INTO vIsFree
		FROM srt.expedition e 
			JOIN srt.buffer b ON b.id = e.bufferFk 
		WHERE e.bufferFk = vBufferFk
			AND e.`position` > 0;

	IF vIsFree AND vBufferType NOT IN('LOADING','STRAPPING') THEN

			UPDATE srt.buffer SET reserve = NULL, routeFk = NULL, dayMinute = NULL 
				WHERE id = vBufferFk;

			CALL srt.buffer_setStateType(vBufferFk,'FREE','DEFAULT');

	END IF;

	SELECT b.typeFk INTO vTypeFk
		FROM srt.buffer b 
		WHERE b.id = vBufferFk;

END$$
DELIMITER ;
