DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`expedition_get`(vAntennaFk INT, OUT vExpeditionOutFk INT )
BEGIN
	
	DECLARE vId INT;
	DECLARE vCount INT;
	DECLARE vCreatedMin DATETIME;
	DECLARE vCreatedMax DATETIME;
	DECLARE vSecondsScope INT DEFAULT 30;
	
	START TRANSACTION;

	SELECT count(DISTINCT lr.code) INTO vCount
		FROM srt.lastRFID lr 
		WHERE lr.antennaFk = vAntennaFk
			AND NOT isConsulted;
	
	CASE vCount
	
		WHEN 0 THEN
		
			SET vExpeditionOutFk = srt.expedition_check(vCount);
		
		WHEN 1 THEN
		
			SELECT CAST(code AS DECIMAL(10,0)), lr.id 
			INTO vExpeditionOutFk, vId
				FROM srt.lastRFID lr 
				WHERE lr.antennaFk = vAntennaFk
					AND NOT isConsulted
			ORDER BY lr.seenCount DESC, lr.peakRssi
			LIMIT 1;	
		
		ELSE
		
		-- Descartamos aquellas lecturas que se han producido unos segundos antes.
		SELECT MIN(created), MAX(created) INTO vCreatedMin, vCreatedMax
			FROM srt.lastRFID lr 
			WHERE lr.antennaFk = vAntennaFk
				AND NOT isConsulted;
			
		UPDATE srt.lastRFID lr 
		 	JOIN (SELECT id, code 
		 			FROM srt.lastRFID
		 			WHERE created 
		 			BETWEEN TIMESTAMPADD(SECOND, - vSecondsScope, vCreatedMin) 
		 				AND TIMESTAMPADD(SECOND, -1, vCreatedMin)
		 			AND isChoosed = 1#
					) sub ON sub.code = lr.code AND sub.id != lr.id
			SET lr.isConsulted = TRUE
			WHERE lr.created BETWEEN vCreatedMin AND vCreatedMax
				AND lr.antennaFk = vAntennaFk;
			
		SELECT CAST(code AS DECIMAL(10,0)), lr.id 
			INTO vExpeditionOutFk, vId
				FROM srt.lastRFID lr 
				WHERE lr.antennaFk = vAntennaFk
					AND NOT isConsulted
			ORDER BY lr.peakRssi DESC, lr.seenCount DESC #
			LIMIT 1;	
		
	END CASE;
	
	UPDATE srt.lastRFID 
		SET isChoosed = TRUE 
		WHERE id = vId;
	
	UPDATE srt.lastRFID 
		SET isConsulted = TRUE 
		WHERE antennaFk = vAntennaFk
			AND NOT isConsulted;

	COMMIT;
	
	INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`, antennaFk) VALUES(vExpeditionOutFk, 0, 'DIM', vAntennaFk);
END$$
DELIMITER ;
