package org.jboss.cache.interceptors;

import org.jboss.cache.Fqn;
import org.jboss.cache.Region;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.buddyreplication.BuddyFqnTransformer;
import org.jboss.cache.eviction.NodeEventType;

/**
 * A subclass of EvictionInterceptor that is aware of and able to deal with buddy regions.
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.2.0
 */
public class BuddyRegionAwareEvictionInterceptor extends EvictionInterceptor
{
   private BuddyFqnTransformer buddyFqnTransformer;

   @Inject
   public void initialize(BuddyFqnTransformer transformer)
   {
      this.buddyFqnTransformer = transformer;
   }

   @Override
   protected Region getRegion(Fqn fqn, NodeEventType type)
   {
      Region r = super.getRegion(fqn, type);
      if (r != null)
         return r;
      else if (buddyFqnTransformer.isBackupFqn(fqn))
      {
         // try and grab a backup region, creating one if need be.
         Fqn actualFqn = buddyFqnTransformer.getActualFqn(fqn);
         Fqn backupRoot = buddyFqnTransformer.getBackupRootFromFqn(fqn);

         // the actual region could be a few levels higher than actualFqn
         Region actualRegion = regionManager.getRegion(actualFqn, Region.Type.EVICTION, false);

         if (actualRegion == null) return null;

         //create a new region for this backup
         Region newRegion = regionManager.getRegion(Fqn.fromRelativeFqn(backupRoot, actualRegion.getFqn()), Region.Type.EVICTION, true);
         newRegion.setEvictionPolicy(actualRegion.getEvictionPolicyConfig());

         return newRegion;
      }
      else return null;
   }
}
