DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`roadmap_cloneDay`(
	vDateToCopy DATE,
	vDateToPaste DATE
)
BEGIN
/**
 * Clona roadmaps de un día a otro, incluyendo las paradas y sin algunos
 * campos de la tabla principal, como matrículas, conductores...
 *
 * @param vDateToCopy Fecha para copiar
 * @param vDateToPaste Fecha para pegar
 */
	DECLARE vDaysDiff INT;
	DECLARE vNextRoadmapId INT;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	SET vDaysDiff = DATEDIFF(vDateToPaste, vDateToCopy);

	IF vDaysDiff IS NULL OR NOT vDaysDiff THEN
		CALL util.throw("No valid dates");
	END IF;

	START TRANSACTION;

	SELECT AUTO_INCREMENT INTO vNextRoadmapId
		FROM information_schema.tables
		WHERE table_name = 'roadmap'
			AND table_schema = 'vn';

	CREATE OR REPLACE TEMPORARY TABLE tmp.roadmapsToCopy
		ENGINE = MEMORY
		SELECT ROW_NUMBER() OVER(ORDER BY id) rowOrder,
				id,
				`name`,
				roadmapAddressFk,
				etd,
				eta,
				observations,
				price
			FROM roadmap
				WHERE etd BETWEEN vDateToCopy AND util.dayEnd(vDateToCopy);

	INSERT INTO roadmap (`name`, roadmapAddressFk, etd, eta, observations, price)
		SELECT `name`,
				roadmapAddressFk,
				etd + INTERVAL vDaysDiff DAY,
				eta + INTERVAL vDaysDiff DAY,
				observations,
				price
			FROM tmp.roadmapsToCopy;

	INSERT INTO roadmapStop (roadmapFk, roadmapAddressFk, eta, `description`, bufferFk)
		SELECT (rtc.rowOrder - 1) + vNextRoadmapId,
				rs.roadmapAddressFk,
				rs.eta + INTERVAL vDaysDiff DAY,
				rs.description,
				rs.bufferFk
			FROM tmp.roadmapsToCopy rtc
				JOIN roadmapStop rs ON rs.roadmapFk = rtc.id;

	COMMIT;

	DROP TEMPORARY TABLE tmp.roadmapsToCopy;
END$$
DELIMITER ;
