
DROP procedure IF EXISTS vn.`zoneClosure_recalc`;

DELIMITER $$
CREATE DEFINER=`root`@`%` 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 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;
    
    REPEAT
		CALL zone_getOptionsForShipment(vShipped);
		INSERT INTO zoneClosure(zoneFk, dated, `hour`)
			SELECT zoneFk, vShipped, `hour` FROM tmp.zoneOption;
		
        SET vCounter = vCounter + 1;
        SET vShipped = TIMESTAMPADD(DAY, 1, vShipped);
	UNTIL vCounter > vScope
    END REPEAT;
    
    DROP TEMPORARY TABLE tmp.zone;
	DO RELEASE_LOCK('vn.zoneClosure_recalc');
END$$

DELIMITER ;

