import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.Declarable;
import com.gemstone.gemfire.cache.EntryEvent;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionEvent;
import com.gemstone.gemfire.cache.RegionExistsException;

import com.gemstone.gemfire.cache.util.CacheListenerAdapter;

import java.util.Map;
import java.util.Properties;

public class CreateRegionCacheListener extends CacheListenerAdapter<String,RegionAttributes> implements Declarable {

  private Cache cache;
  
  public CreateRegionCacheListener() {
    this.cache = CacheFactory.getAnyInstance();
  }

  public void afterCreate(EntryEvent<String,RegionAttributes> event) {
    createRegion(event.getKey(), event.getNewValue());
  }
  
  public void afterDestroy(EntryEvent<String,RegionAttributes> event) {
    Region region = this.cache.getRegion(event.getKey());
    if (region != null) {
      region.localDestroyRegion();
    }
  }
  
  public void afterRegionCreate(RegionEvent<String,RegionAttributes> event) {
    Region<String,RegionAttributes> region = event.getRegion();
    for (Map.Entry<String,RegionAttributes> entry : region.entrySet()) {
      createRegion(entry.getKey(), entry.getValue());
    }
  }
  
  private void createRegion(String regionName, RegionAttributes attributes) {
    if (this.cache.getLogger().fineEnabled()) {
      this.cache.getLogger().fine("CreateRegionCacheListener creating region named: " + regionName + " with attributes: " + attributes);
    }
    try {
      Region region = this.cache.createRegion(regionName, attributes);
      if (this.cache.getLogger().fineEnabled()) {
        this.cache.getLogger().fine("CreateRegionCacheListener created: " + region);
      }
      if (this.cache.getLogger().fineEnabled()) {
				this.cache.getLogger().fine("CreateRegionCacheListener created: " + region);
			}
    } catch (RegionExistsException e) {/* ignore */}
  }
  
  private void destroyRegion(String regionName) {
    if (this.cache.getLogger().fineEnabled()) {
      this.cache.getLogger().fine("CreateRegionCacheListener destroying region named: " + regionName);
    }
    Region region = this.cache.getRegion(regionName);
    if (region != null) {
      region.localDestroyRegion();
			if (this.cache.getLogger().fineEnabled()) {
				this.cache.getLogger().fine("CreateRegionCacheListener destroyed: " + region);
			}
    }
  }

  public void init(Properties p) {
  }
}
