DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `srt`.`expedition_relocate`(vExpeditionFk INT, vBufferToFk INT)
proc:BEGIN
	
	/**
	 * Asigna buffer destino nuevo para una expedición
	 * 
	 * @param vExpeditionFk Identificacion de srt.expedition
	 *
	 * @param vBufferToFk Identificador de srt.buffer
	 * 
	 */
	
	DECLARE vBufferFromFk INT;

	START TRANSACTION;

	IF (SELECT COUNT(*) FROM srt.moving WHERE expeditionFk = vExpeditionFk) THEN
	
		LEAVE proc;
	
	END IF;

	SELECT e.bufferFk INTO vBufferFromFk
		FROM srt.expedition e 
		WHERE e.id = vExpeditionFk;

	SET vBufferToFk = IFNULL(vBufferToFk, IFNULL(srt.bufferPool_get(), `srt`.`buffer_get`(vExpeditionFk)));

	IF vBufferFromFk = vBufferToFk THEN

		LEAVE proc;
	
	END IF;

	REPLACE srt.moving (expeditionFk, 
						bufferFromFk, 
						bufferToFk, 
						stateFk)
		SELECT 	e.id, 
				e.bufferFk, 
				vBufferToFk,
				ms.id 
			FROM srt.expedition e 
				JOIN srt.movingState ms ON ms.description = 'NEW'
				LEFT JOIN srt.moving m ON m.expeditionFk 
			WHERE e.id = vExpeditionFk;
	
	UPDATE srt.expedition e
		JOIN srt.expeditionState es on es.description = 'ENTERING'
		JOIN srt.moving m ON m.expeditionFk = e.id
		SET e.stateFk = es.id
		WHERE e.id = vExpeditionFk;
	
	COMMIT;

	IF srt.buffer_isFull(vBufferToFk) THEN  
	
		CALL srt.buffer_setStateType(vBufferToFk,'FULL', NULL);
	
	END IF;

END$$
DELIMITER ;
