DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `srt`.`expedition_bufferOut`(vBufferToFk INT)
BEGIN
	
	/**
	 * Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de ese buffer
	 *
	 * @param vBufferToFk Identificador de srt.buffer
	 */
		
  	DECLARE vExpListFk INT;
  
  	DECLARE vExpBufFk INT;
  
	DECLARE vDone INT DEFAULT FALSE;
	  
  	DECLARE vExpList CURSOR FOR 
  		SELECT bs.expeditionFk
  			FROM srt.bufferStock bs 
  				JOIN srt.expedition e ON e.id = bs.expeditionFk
  				LEFT JOIN srt.moving m ON m.expeditionFk = bs.expeditionFk
  			WHERE bs.routeBuffer = vBufferToFk
  				AND ISNULL(m.expeditionFk)
				AND bs.typeName = 'ACCUMULATION'
  				ORDER BY (vBufferToFk - e.bufferFk),
  						e.`position` ;
  
  	DECLARE vExpBuf CURSOR FOR
  		SELECT e.id
  			FROM srt.expedition e 
  				JOIN srt.expedition e2 ON e2.bufferFk = e.bufferFk 
  				LEFT JOIN srt.moving m ON m.expeditionFk = e.id
  			WHERE e2.id = vExpListFk
  				AND ISNULL(m.expeditionFk)
  				AND e.`position` <= e2.`position` 
	  		ORDER BY e.`position`;
  			
  	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    	
 	OPEN vExpList;
 
 	FETCH vExpList INTO vExpListFk;
 
 	WHILE NOT vDone DO
  	
  		OPEN vExpBuf;
  	
  		FETCH vExpBuf INTO vExpBufFk;
  	
  		WHILE NOT vDone DO
  		
  			IF vExpBufFk = vExpListFk THEN
  			
  				CALL srt.expedition_relocate(vExpListFk, vBufferToFk);
  			
  				SET vDone = TRUE;
  			
  			ELSE
  			
  				CALL srt.expedition_relocate(vExpBufFk, NULL);
  			
  				SET vDone = FALSE; 
  		
  				FETCH vExpBuf INTO vExpBufFk;
  			
  			END IF;
  		
  		END WHILE;
    
  		CLOSE vExpBuf;
  	
  		SET vDone = FALSE; 
   
  		FETCH vExpList INTO vExpListFk;
  		
  	END WHILE;

	CLOSE vExpList;


END$$
DELIMITER ;
