DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `srt`.`buffer_get`(vExpeditionFk INT)
	RETURNS int(11)
	NOT DETERMINISTIC
	READS SQL DATA
BEGIN
/**
 * Devuelve el buffer destino para una expedición
 *
 * @param vExpeditionFk Identificador de srt.expedition
 * @return Identificador de srt.buffer
 */
	DECLARE vBufferToFk INT;
	DECLARE vBufferFromFk INT;
	DECLARE vBufferGroup INT;
	DECLARE vBufferStrapping INT;

	SELECT IFNULL(rm.bufferFk, c.bufferDefault), IFNULL(e.bufferFk,0)
		INTO vBufferToFk, vBufferFromFk
		FROM srt.expedition e 
			LEFT JOIN vn.expedition e2 ON e2.id = e.id
			LEFT JOIN vn.ticket t ON t.id = e2.ticketFk
			LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
			JOIN srt.config c
		WHERE e.id = vExpeditionFk;

	SELECT `group` INTO vBufferGroup 
		FROM srt.bufferGroup 
		WHERE bufferFk = vBufferToFk;

	SELECT bg.bufferFk
		INTO vBufferStrapping
		FROM srt.bufferGroup bg
			JOIN srt.buffer b ON b.id = bg.bufferFk
			JOIN srt.bufferType bt ON bt.id = b.typeFk
		WHERE bt.typeName = 'STRAPPING'
			AND bg.`group` = vBufferGroup
		LIMIT 1;

	IF vBufferGroup THEN 
		SELECT sub.bufferFk INTO vBufferToFk
			FROM (
				SELECT b.id bufferFk,
						count(DISTINCT e.id) expeditions,
						bs.description,
						bt.typeName,
						b.motors
					FROM srt.buffer b
						JOIN srt.bufferType bt ON bt.id = b.typeFk 
						JOIN srt.bufferState bs ON bs.id = b.stateFk 
						JOIN srt.bufferGroup bg ON bg.bufferFk = b.id
						LEFT JOIN srt.expedition e ON e.bufferFk = b.id
						LEFT JOIN srt.moving m ON m.bufferFromFk = b.id
					WHERE bg.`group` = vBufferGroup
						AND b.id != vBufferFromFk
						AND bt.isTarget
						AND m.id IS NULL
					GROUP BY b.id) sub 
				JOIN srt.config c
				ORDER BY (sub.description = 'FREE') DESC,
						(sub.typeName = ('STRAPPING')) DESC,
						IF(c.isBalanced , sub.expeditions, -sub.expeditions),
						ABS(sub.bufferFk - vBufferStrapping)
			LIMIT 1;
	END IF;

	RETURN vBufferToFk;

END$$
DELIMITER ;
