DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`zoneClosure_recalc`()
proc: BEGIN
/**
 * Recalculates the delivery time (hour) for every zone in days + scope in future
 */
    DECLARE vScope INT;
    DECLARE vCounter INT DEFAULT 0;
    DECLARE vShipped DATE DEFAULT util.VN_CURDATE();

	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
    BEGIN
		DO RELEASE_LOCK('vn.zoneClosure_recalc');
        RESIGNAL;
	END;

	IF NOT GET_LOCK('vn.zoneClosure_recalc', 0) THEN
		LEAVE proc;
	END IF;

	SELECT scope INTO vScope
		FROM zoneConfig;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.zone;
    CREATE TEMPORARY TABLE tmp.zone
		(INDEX (id))
		ENGINE = MEMORY
        SELECT id FROM zone;
              
	TRUNCATE TABLE zoneClosure;
    
    WHILE vCounter <= vScope DO
    
		CALL zone_getOptionsForShipment(vShipped, TRUE);
        
		REPLACE zoneClosure(zoneFk, dated, `hour`)
			SELECT zoneFk, vShipped, `hour` 
				FROM tmp.zoneOption;
		
        SET vCounter = vCounter + 1;
        SET vShipped = TIMESTAMPADD(DAY, 1, vShipped);
    END WHILE;
    
    -- DROP TEMPORARY TABLE tmp.zone;
	DO RELEASE_LOCK('vn.zoneClosure_recalc');
END$$
DELIMITER ;
