DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `srt`.`randomMoving`(vBufferMin INT, vBufferMax INT)
BEGIN
	DECLARE vBufferOld INT DEFAULT 0;
	DECLARE vBufferFk INT;
	DECLARE vExpeditionFk INT;

	SELECT e.id INTO vExpeditionFk
		FROM srt.expedition e
			LEFT JOIN srt.moving m ON m.expeditionFk = e.id
			JOIN srt.buffer b ON b.id = e.bufferFk
			JOIN srt.bufferType bt ON bt.id = b.typeFk
		WHERE e.bufferFk BETWEEN vBufferMin AND vBufferMax
			AND m.id IS NULL
			AND bt.typeName = 'ACCUMULATION'
			AND b.isActive
		ORDER BY e.`position`, e.updated
		LIMIT 1;

	SELECT IFNULL(e.bufferFk,0) INTO vBufferOld
		FROM srt.expedition e
		WHERE e.id = vExpeditionFk;

	SELECT b.id INTO vBufferFk
		FROM srt.buffer b
			JOIN srt.bufferFreeLength bfl ON bfl.bufferFk = b.id
			JOIN srt.bufferType bt ON bt.id = b.typeFk
			JOIN srt.config c
			LEFT JOIN srt.moving m ON m.bufferToFk = b.id
			LEFT JOIN srt.moving m2 ON m2.bufferFromFk = b.id
		WHERE ISNULL(m.bufferToFk)
			AND ISNULL(m2.bufferFromFk)
			AND b.id BETWEEN vBufferMin AND vBufferMax
			AND b.id != vBufferOld
			AND b.isActive
			AND bt.typeName = 'ACCUMULATION'
			AND bfl.freeLength > c.freeLength * 2
		ORDER BY (b.id = floor(MINUTE(util.VN_NOW())/2)) DESC
		LIMIT 1;

	IF vBufferFk THEN

		INSERT INTO srt.moving (expeditionFk, bufferFromFk, bufferToFk)
			SELECT e.id, e.bufferFk, vBufferFk
			FROM srt.expedition e
			WHERE e.id = vExpeditionFk;

	END IF;
END$$
DELIMITER ;
