DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`expedition_arrived`(vExpeditionFk INT, vBufferFk INT, OUT vTypeFk INT)
BEGIN
/**
 * La expedición ha entrado en un buffer, superando fc2
 *
 * @param vExpeditionFk Identificador de srt.expedition
 * @param vBufferFk Identificador de srt.buffer
 * 
 * @return vTypeFk Identificador de srt.bufferType
 * 
 */
	DECLARE vComingBoxes INT;
	DECLARE vHasWorkerWaiting BOOL;
	DECLARE vIsRandomMoving BOOL;
	DECLARE vState VARCHAR(15);
	DECLARE vType VARCHAR(15);
	DECLARE visBufferWhithoutBoxesCount BOOL;

	IF vBufferFk = 1 THEN
		SET vBufferFk = 0;	
	END IF;

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

	SELECT COUNT(*) INTO vComingBoxes
		FROM srt.moving m
			WHERE m.bufferToFk = vBufferFk
				AND m.expeditionFk != vExpeditionFk;

	SELECT b.hasWorkerWaiting,
			c.isRandomMoving ,
			(bt.typeName = 'STRAPPING') OR vBufferFk IN (c.bufferNoLabels, c.bufferTwoLabels, c.bufferDefault)
		INTO 	vHasWorkerWaiting,
				vIsRandomMoving,
				visBufferWhithoutBoxesCount
		FROM srt.buffer b
			JOIN srt.bufferType bt ON bt.id = b.typeFk
			JOIN srt.config c
			WHERE b.id = vBufferFk
		LIMIT 1;

	SET vState = IF(srt.buffer_isFull(vBufferFk), 'FULL', 'FREE');

	SET vType = IF(vHasWorkerWaiting 
					AND NOT vComingBoxes 
					AND NOT vIsRandomMoving
					AND vState = 'FULL', 'UNLOADING', 'ACCUMULATION');

	IF NOT visBufferWhithoutBoxesCount THEN
		CALL srt.buffer_setStateType(vBufferFk,vState,vType);
	END IF;

	UPDATE srt.expedition e
		JOIN srt.expeditionState es ON es.description = 'STORED'
		SET e.bufferFk = IF(visBufferWhithoutBoxesCount,0,vBufferFk),
			e.`position` = 0,
			e.stateFk = es.id
		WHERE e.id = vExpeditionFk;

	UPDATE srt.expedition e 
		SET e.`position` = e.`position` + 1
		WHERE e.bufferFk = vBufferFk
			AND e.bufferFk > 0;

	INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
		SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'ARRIVED' 
			FROM srt.moving 
			WHERE expeditionFk = vExpeditionFk
		ORDER BY id DESC 
		LIMIT 1;

	DELETE FROM srt.moving 
		WHERE expeditionFk = vExpeditionFk;

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

END$$
DELIMITER ;
