DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`moving_clean`()
BEGIN
/**
 * Elimina movimientos por inactividad
 *
 */
	DECLARE vExpeditionFk INT;
	DECLARE vBufferToFk INT;
	DECLARE vBufferFromFk INT;
	DECLARE done BOOL DEFAULT FALSE;

	DECLARE cur CURSOR FOR
		SELECT m.expeditionFk, m.bufferToFk, m.bufferFromFk
			FROM srt.moving m
			JOIN srt.config c
			JOIN (SELECT bufferFk, SUM(isActive) hasBox
					FROM srt.photocell
					GROUP BY bufferFk) sub ON sub.bufferFk = m.bufferFromFk
			WHERE m.created < TIMESTAMPADD(MINUTE, - c.movingMaxLife , util.VN_NOW())
				AND NOT sub.hasBox;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

	OPEN cur;

	bucle: LOOP

		FETCH cur INTO vExpeditionFk, vBufferToFk, vBufferFromFk;

		IF done THEN
			LEAVE bucle;
		END IF;

		DELETE FROM srt.moving 
			WHERE expeditionFk = vExpeditionFk;

		UPDATE srt.expedition e 
			JOIN srt.expeditionState es ON es.description = 'OUT'
			SET
				bufferFk = NULL,
				`position` = NULL,
				stateFk = es.id
			WHERE e.id = vExpeditionFk;

		UPDATE srt.expedition e
			SET e.`position` = e.`position` - 1
			WHERE e.bufferFk = vBufferFromFk
				AND e.`position` > 0;

		CALL vn.mail_insert(
				'pako@verdnatura.es, carles@verdnatura.es',
				NULL,
				CONCAT('Moving_clean. Expedition: ', vExpeditionFk, ' estaba parada'),
				CONCAT('Expedition: ', vExpeditionFk,' vBufferToFk: ', vBufferToFk)
			);

	END LOOP bucle;

	CLOSE cur;

END$$
DELIMITER ;
