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 vRoadmapFk INT;
	DECLARE vNewRoadmapFk INT;
	DECLARE vDone BOOL DEFAULT FALSE;
	DECLARE vRoadmaps CURSOR FOR
		SELECT id
			FROM roadmap
			WHERE etd BETWEEN vDateToCopy AND util.dayEnd(vDateToCopy);

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	SET vDaysDiff = DATEDIFF(vDateToPaste, vDateToCopy);

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

	START TRANSACTION;

	OPEN vRoadmaps;
	l: LOOP
		SET vDone = FALSE;
		FETCH vRoadmaps INTO vRoadmapFk;

		IF vDone THEN
			LEAVE l;
		END IF;

	INSERT INTO roadmap (`name`, roadmapAddressFk, etd, eta, observations, price)
		SELECT `name`,
				roadmapAddressFk,
				etd + INTERVAL vDaysDiff DAY,
				eta + INTERVAL vDaysDiff DAY,
				observations,
				price
			FROM roadmap
			WHERE id = vRoadmapFk;

	SET vNewRoadmapFk = LAST_INSERT_ID();

	INSERT INTO roadmapStop (roadmapFk, roadmapAddressFk, eta, `description`, bufferFk)
		SELECT vNewRoadmapFk,
				roadmapAddressFk,
				eta + INTERVAL vDaysDiff DAY,
				`description`,
				bufferFk
			FROM roadmapStop
			WHERE roadmapFk = vRoadmapFk;
	END LOOP;
	CLOSE vRoadmaps;

	COMMIT;
END$$
DELIMITER ;
