DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`getTimeBetweenRoadmapAddresses`(
	vRoadmapAddressFrom INT,
	vRoadmapAddressTo INT
)
	RETURNS int(11)
	DETERMINISTIC
BEGIN
/**
 * Retorna el tiempo en segundos que se suele tardar en ir
 * de un punto de distribución a otro en una ruta troncal.
 *
 * @param vRoadmapAddressFrom Punto de distribución de origen
 * @param vRoadmapAddressTo Punto de distribución de destino
 * @return Tiempo en segundos
 */
	DECLARE vSeconds INT;

	WITH wRoadmap AS (
		SELECT ROW_NUMBER() OVER(PARTITION BY roadmapFk ORDER BY eta) `sequence`,
				roadmapFk,
				roadmapAddressFk,
				eta
			FROM vn.roadmapStop
	)
	SELECT AVG(TIME_TO_SEC(TIMEDIFF(rTo.eta, rFrom.eta))) INTO vSeconds
		FROM wRoadmap rFrom
			JOIN wRoadmap rTo ON rTo.roadmapFk = rFrom.roadmapFk
		WHERE rFrom.roadmapAddressFk = vRoadmapAddressFrom
			AND rTo.roadmapAddressFk = vRoadmapAddressTo
			AND rFrom.`sequence` + 1 = rTo.`sequence`;

	RETURN vSeconds;
END$$
DELIMITER ;
