DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`(
	vSelf INT,
	vParkingFk INT
)
BEGIN
/**
 * Aparca un ticket en un parking.
 *
 * @param vSelf Id ticket
 * @param vParkingFk Id parking
 */
	DECLARE vDone INT DEFAULT FALSE;
	DECLARE vCollectionTicketFk INT;
	DECLARE vCursor CURSOR FOR
		SELECT IFNULL(tc2.ticketFk, t.id)
			FROM ticket t
				LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id
				LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk
			WHERE t.id = vSelf;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		RESIGNAL;
	END;

	INSERT INTO vn.ticketParking(ticketFk, parkingFk)
		SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk
			FROM ticket t
				LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id
				LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk
			WHERE t.id = vSelf
		ON DUPLICATE KEY UPDATE parkingFk = vParkingFk;

	OPEN vCursor;
	l: LOOP
		FETCH vCursor INTO vCollectionTicketFk;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL vn.ticket_setNextState(vCollectionTicketFk);
	END LOOP;

	CLOSE vCursor;
END$$
DELIMITER ;
