DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`moving_next`()
BEGIN

	DECLARE vExpeditionFk INT;
	DECLARE vMovingFk INT;
	DECLARE vSecondsFromLastRFIDReading INT;
	
	CALL srt.randomMoving_Launch();

	CALL srt.moving_GroupOut();

	CALL srt.moving_CollidingSet();

	SELECT TIME_TO_SEC((TIMEDIFF(util.VN_NOW(),MAX(lr.created))))
		INTO vSecondsFromLastRFIDReading
		FROM srt.lastRFID lr;
	
	
	SELECT m.id INTO vMovingFk
		FROM srt.moving m
			JOIN srt.expedition e ON e.id = m.expeditionFk
			JOIN srt.movingState ms ON ms.id = m.stateFk
			JOIN srt.buffer b ON b.id = m.bufferToFk
			JOIN srt.buffer b2 ON b2.id = m.bufferFromFk
			JOIN srt.bufferType bt ON bt.id = b.typeFk 
			JOIN srt.bufferState bs ON bs.id = b.stateFk 
		JOIN srt.config c 
		WHERE NOT ms.isInterfering 
			AND NOT m.isColliding
			AND (c.isEnteringBlocked = FALSE OR m.bufferFromFk > 0)
			AND (e.`position` = 1 OR m.bufferFromFk = 0)
			AND (vSecondsFromLastRFIDReading > c.enteringSecondsReserve OR m.bufferFromFk = 0)
			AND (bs.description != 'FULL' OR m.bufferFromFk = 0)
		ORDER BY (m.bufferFromFk = 0) DESC, 
			m.bufferFromFk DESC
	LIMIT 1;

    SELECT m.expeditionFk 
		INTO vExpeditionFk
		FROM moving m
			WHERE m.id = vMovingFk;
    
	IF vExpeditionFk THEN
    
		SELECT m.expeditionFk,
			m.bufferFromFk,
	       	m.bufferToFk
				FROM moving m
		            WHERE m.id = vMovingFk;
	           
	    UPDATE expedition e
			JOIN expeditionState es ON es.description = 'MOVING'
			SET e.stateFk = es.id
	        WHERE e.id = vExpeditionFk;
	       
	    UPDATE srt.moving m
			JOIN srt.movingState ms ON ms.description = 'MOVING'
			SET m.stateFk = ms.id
	        WHERE m.id = vMovingFk;
	    
	    INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
			SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'NEXT' 
				FROM srt.moving 
				WHERE id = vMovingFk;
	
	ELSE
	
		SELECT 0 expeditionFk, 0 bufferFromFk, 0 bufferToFk;
	
	END IF;
          
END$$
DELIMITER ;
