package org.jboss.cache.interceptors;

import org.jboss.cache.DataContainer;
import org.jboss.cache.Fqn;
import org.jboss.cache.InvocationContext;
import org.jboss.cache.NodeSPI;
import org.jboss.cache.commands.write.EvictCommand;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.notifications.Notifier;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Writes evicted nodes back to the store on the way in through the
 * CacheLoader, either before each method call (no TXs), or at TX commit.
 *
 * @author <a href="mailto:{hmesha@novell.com}">{Hany Mesha}</a>
 * @version $Id: PassivationInterceptor.java 6000 2008-06-17 23:43:54Z manik.surtani@jboss.com $
 */
public class PassivationInterceptor extends CommandInterceptor implements PassivationInterceptorMBean
{

   private final AtomicLong passivations = new AtomicLong(0);

   protected CacheLoader loader;
   private Notifier notifier;
   private DataContainer dataContainer;

   @Inject
   public void setDependencies(Notifier notifier, DataContainer dataContainer, CacheLoaderManager loaderManager)
   {
      this.notifier = notifier;
      this.dataContainer = dataContainer;
      this.loader = loaderManager.getCacheLoader();
   }

   /**
    * Notifies the cache instance listeners that the evicted node is about to
    * be passivated and stores the evicted node and its attributes back to the
    * store using the CacheLoader.
    */
   @Override
   public Object visitEvictFqnCommand(InvocationContext ctx, EvictCommand command) throws Throwable
   {
      if (command.isRecursive())
      {
         List<Fqn> fqnsToEvict = dataContainer.getNodesForEviction(command.getFqn(), true);
         if (fqnsToEvict != null)
         {
            for (Fqn f : fqnsToEvict)
            {
               passivate(ctx, f);
            }
         }
      }
      else
      {
         passivate(ctx, command.getFqn());
      }

      return invokeNextInterceptor(ctx, command);
   }

   private void passivate(InvocationContext ctx, Fqn fqn) throws Throwable
   {
      try
      {
         // evict method local doesn't hold attributes therefore we have
         // to get them manually
         Map attributes = getNodeAttributes(fqn);
         // notify listeners that this node is about to be passivated
         notifier.notifyNodePassivated(fqn, true, attributes, ctx);
         if (trace) log.trace("Passivating " + fqn);
         loader.put(fqn, attributes);
         notifier.notifyNodePassivated(fqn, false, Collections.emptyMap(), ctx);
         if (getStatisticsEnabled()) passivations.getAndIncrement();
      }
      catch (NodeNotLoadedException e)
      {
         if (trace)
         {
            log.trace("Node " + fqn + " not loaded in memory; passivation skipped");
         }
      }
   }

   public long getPassivations()
   {
      return passivations.get();
   }

   @Override
   public void resetStatistics()
   {
      passivations.set(0);
   }

   @Override
   public Map<String, Object> dumpStatistics()
   {
      Map<String, Object> retval = new HashMap<String, Object>();
      retval.put("Passivations", passivations.get());
      return retval;
   }

   /**
    * Returns attributes for a node.
    */
   private Map getNodeAttributes(Fqn fqn) throws NodeNotLoadedException
   {
      if (fqn == null)
      {
         throw new NodeNotLoadedException();
      }
      NodeSPI n = dataContainer.peek(fqn, true, false);

      if (n != null)
      {
         return n.getDataDirect();
      }
      else
      {
         throw new NodeNotLoadedException();
      }
   }

   private static class NodeNotLoadedException extends Exception
   {
      /**
       * The serialVersionUID
       */
      private static final long serialVersionUID = -4078972305344328905L;
   }
}
