DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`VN_SCHEDULER`()
BEGIN
    DECLARE vDone BOOL;
	DECLARE vError VARCHAR(255) DEFAULT NULL;
	DECLARE vErrorCode VARCHAR(255) DEFAULT NULL;
	DECLARE vSchema VARCHAR(255);
	DECLARE vStatus VARCHAR(255);
	DECLARE vProcedure VARCHAR(255);
	-- DECLARE vLogMail VARCHAR(255);
	DECLARE vScheduleFk INT;
    -- Obtener datos de la tabla vn_schedules
    DECLARE vQueue CURSOR FOR
		SELECT id, `schema`, `procedure`, `status`
			FROM vn_schedules
			WHERE status = 'scheduled';

    OPEN vQueue;
        l: LOOP
            SET vDone = FALSE;
            FETCH vQueue INTO vScheduleFk, vSchema, vProcedure, vStatus;

            IF vDone THEN
                LEAVE l;
            END IF;

            UPDATE  vn_schedules
                SET `started` = util.VN_NOW(),
                    `finished` = NULL,
                    `error` = NULL,
                    `errorCode` = NULL
                WHERE id = vScheduleFk;

            SET vError = NULL;
       DECLARE EXIT HANDLER FOR SQLEXCEPTION
		GET DIAGNOSTICS CONDITION 1
			vError = MESSAGE_TEXT,
			vErrorCode = RETURNED_SQLSTATE;

        CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`'));

            IF vError IS NOT NULL THEN
                -- IF vLogMail IS NOT NULL THEN
                --     CALL vn.mail_insert(
                --         vLogMail,
                --         NULL,
                --         CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'),
                --         CONCAT(
                --             '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break
                --             'See ', SCHEMA(), '.nightTask table for more info.'
                --         )
                --     );
                -- END IF;

                UPDATE vn_schedules
                    SET `error` = vError,
                        finished = util.VN_NOW(),
                        lastFinished = util.VN_NOW()
                        `errorCode` = vErrorCode
                        `status` = 'error'
                    WHERE id = vScheduleFk;
            ELSE
                UPDATE vn_schedules
                    SET `error` = vError,
                        `errorCode` = vErrorCode
                        finished = util.VN_NOW(),
                        lastFinished = util.VN_NOW(),
                        `status` = 'exec'
                    WHERE id = vScheduleFk;
            END IF;
        END LOOP;
	CLOSE vQueue;
END$$

DELIMITER ;
