package org.jboss.cache.util;

import org.jboss.cache.Cache;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.DataContainerImpl;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.invocation.CacheInvocationDelegate;

/**
 * Helper that prints the contents of a {@link org.jboss.cache.Cache} to a string.
 *
 * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
 * @since 2.0.0
 */
public class CachePrinter
{
   /**
    * Prints the contents of the cache (nodes + data) to a string
    *
    * @param c cache to print
    * @return a String representation of the cache
    */
   public static String printCacheDetails(Cache c)
   {
      // internal cast
      DataContainerImpl ci = (DataContainerImpl) ((CacheInvocationDelegate) c).getDataContainer();
      return ci.printDetails();
   }

   /**
    * Prints the status of locks in the cache (nodes + locks) to a string
    *
    * @param c cache to print
    * @return a String representation of the cache
    */
   public static String printCacheLockingInfo(Cache c)
   {
      // internal cast
      DataContainerImpl cd = (DataContainerImpl) ((CacheInvocationDelegate) c).getDataContainer();
      return cd.printLockInfo();
   }

   public static String printCacheInterceptors(CacheSPI<?, ?> cache)
   {
      StringBuilder b = new StringBuilder();
      int index = 0;
      b.append("\n");
      for (CommandInterceptor i : cache.getInterceptorChain())
      {
         b.append("# ");
         b.append(index);
         b.append(" : ");
         b.append(i);
         b.append("\n");
         index++;
      }
      return b.toString();
   }

   public static String printInterceptorChain(CommandInterceptor i)
   {
      StringBuilder sb = new StringBuilder();
      if (i != null)
      {
         if (i.getNext() != null)
         {
            sb.append(printInterceptorChain(i.getNext())).append("\n");
         }
         sb.append("\t>> ");
         sb.append(i.getClass().getName());
      }
      return sb.toString();
   }
}
