DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `srt`.`expedition_groupOut`(vDayMinute INT, vBufferToFk INT)
BEGIN
	
	/**
	 * Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de la hora pedida
	 *
	 * @param vDayMinute Minuto absoluto del dia
	 * @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
  			WHERE bs.dayMinute = vDayMinute
  				AND bs.expeditionState = 'STORED'
				AND bs.isActive
				AND bs.hasWorkerWaiting = FALSE
				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 
  				JOIN srt.expeditionState es ON es.id = e.stateFk 
  			WHERE e2.id = vExpListFk
  				AND e.`position` <= e2.`position` 
  				AND es.description = 'STORED'
	  		ORDER BY e.`position`;
  			
  	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    	
 	OPEN vExpList;
 
 	FETCH vExpList INTO vExpListFk;
 
 	UPDATE srt.moving m 
 		JOIN srt.movingState ms ON ms.id = m.stateFk 
 			SET m.bufferToFk = vBufferToFk
 		WHERE m.expeditionFk = vExpListFk
 			AND ms.isRedirectable
 			AND m.bufferFromFk != vBufferToFk;
 
  	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 ;
