DROP procedure IF EXISTS `vn`.`zoneNestTown`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zoneNestTown`()
BEGIN

	DECLARE vDone BOOL;
    DECLARE vParent INT DEFAULT 1;
    DECLARE vGeoFk INT;
    DECLARE vChildFk INT;
    DECLARE vChildName VARCHAR(100);
	DECLARE townCur CURSOR FOR
		SELECT p.geoFk, t.id, t.`name`
			FROM vn.town t 
				JOIN vn.province p ON p.id = t.provinceFk
				JOIN tmp.country tc ON tc.id = p.countryFk
			ORDER BY p.geoFk, t.`name`;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
    -- Remove existing towns from zoneGeo
	DELETE zg FROM vn.town t 
		JOIN vn.province p ON p.id = t.provinceFk
		JOIN tmp.country tc ON tc.id = p.countryFk
		JOIN tmp.zoneGeo zg ON zg.id = t.geoFk;
			
	-- Reset town geoFk
	UPDATE vn.town t 
		JOIN vn.province p ON p.id = t.provinceFk
		JOIN tmp.country tc ON tc.id = p.countryFk
			SET t.geoFk = NULL 
		WHERE t.geoFk IS NOT NULL;

	-- > Town cursor start
	OPEN townCur;
	
	townLoop: LOOP
		SET vDone = FALSE;
        
		FETCH townCur INTO vParent, vChildFk, vChildName;
		
		IF vDone THEN
			LEAVE townLoop;
		END IF;
		
		CALL nst.nodeAdd('tmp', 'zoneGeo', vParent, vChildName);
	END LOOP;
	CLOSE townCur;
	-- < Town cursor end
	
	UPDATE town t
		JOIN tmp.zoneGeo z ON z.name = t.name
		LEFT JOIN province p ON p.geoFk = z.id
			SET t.geoFk = z.id
		WHERE p.geoFk IS NULL;
END$$

DELIMITER ;

