/*
 * JBoss, the OpenSource J2EE webOS
 * 
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.statetransfer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.cache.NodeSPI;
import org.jboss.cache.Version;
import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.marshall.NodeData;
import org.jboss.cache.marshall.NodeDataExceptionMarker;

import java.io.ObjectOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DefaultStateTransferGenerator implements StateTransferGenerator
{

   public static final short STATE_TRANSFER_VERSION = Version.getVersionShort("2.0.0.GA");

   private Log log = LogFactory.getLog(getClass().getName());

   private CacheSPI cache;

   private Set<Fqn> internalFqns;

   protected DefaultStateTransferGenerator(CacheSPI cache)
   {
      this.cache = cache;
      this.internalFqns = cache.getInternalFqns();
   }

   public void generateState(ObjectOutputStream out, Node rootNode, boolean generateTransient,
                             boolean generatePersistent, boolean suppressErrors) throws Throwable
   {
      Fqn fqn = rootNode.getFqn();
      try
      {
         cache.getMarshaller().objectToObjectStream(STATE_TRANSFER_VERSION, out);
         if (generateTransient)
         {
            //transient + marker
            if (log.isTraceEnabled())
            {
               log.trace("writing transient state for " + fqn);
            }
            marshallTransientState((NodeSPI) rootNode, out);
            delimitStream(out);

            if (log.isTraceEnabled())
            {
               log.trace("transient state succesfully written");
            }

            //associated + marker
            if (log.isTraceEnabled())
            {
               log.trace("writing associated state");
            }

            marshallAssociatedState(fqn, out);
            delimitStream(out);

            if (log.isTraceEnabled())
            {
               log.trace("associated state succesfully written");
            }

         }
         else
         {
            //we have to write two markers for transient and associated
            delimitStream(out);
            delimitStream(out);
         }

         CacheLoader cacheLoader = cache.getCacheLoaderManager() == null ? null : cache.getCacheLoaderManager().getCacheLoader();
         if (cacheLoader != null && generatePersistent)
         {
            if (log.isTraceEnabled())
            {
               log.trace("writing persistent state for " + fqn + ",using " + cache.getCacheLoaderManager().getCacheLoader().getClass());
            }

            if (fqn.isRoot())
            {
               cacheLoader.loadEntireState(out);
            }
            else
            {
               cacheLoader.loadState(fqn, out);
            }

            if (log.isTraceEnabled())
            {
               log.trace("persistent state succesfully written");
            }
         }
         delimitStream(out);
      }
      catch (Throwable t)
      {
         cache.getMarshaller().objectToObjectStream(new NodeDataExceptionMarker(t, cache.getLocalAddress()), out);
         throw t;
      }
   }

   /**
    * Places a delimiter marker on the stream
    *
    * @param out stream
    * @throws IOException if there are errs
    */
   protected void delimitStream(ObjectOutputStream out) throws Exception
   {
      cache.getMarshaller().objectToObjectStream(StateTransferManager.STREAMING_DELIMITER_NODE, out);
   }

   /**
    * Do a preorder traversal: visit the node first, then the node's children
    *
    * @param out
    * @throws Exception
    */
   protected void marshallTransientState(NodeSPI node, ObjectOutputStream out) throws Exception
   {
      List<NodeData> nodeData = new LinkedList<NodeData>();
      generateNodeDataList(node, nodeData);
      cache.getMarshaller().objectToObjectStream(nodeData, out, node.getFqn());
   }

   protected void generateNodeDataList(NodeSPI<?, ?> node, List<NodeData> list) throws Exception
   {
      if (internalFqns.contains(node.getFqn()))
      {
         return;
      }

      Map attrs;
      NodeData nd;

      // first handle the current node
      attrs = node.getInternalState(false);

      if (attrs.size() == 0)
      {
         nd = new NodeData(node.getFqn());
      }
      else
      {
         nd = new NodeData(node.getFqn(), attrs);
      }

      list.add(nd);

      // then visit the children
      for (NodeSPI child : node.getChildrenDirect()) generateNodeDataList(child, list);
   }

   /**
    * Does nothing in this base class; can be overridden in a subclass.
    */
   protected void marshallAssociatedState(Fqn fqn, ObjectOutputStream baos) throws Exception
   {
      // no-op in this base class      
   }
}
