package org.jboss.cache.pojo.demo;

import bsh.EvalError;
import bsh.Interpreter;
import org.jboss.cache.notifications.annotation.CacheListener;

import java.util.Map;
import java.util.TreeMap;

/**
 * View for PojoCache demo.
 *
 * @author <a href="mailto:galder.zamarreno@jboss.com">Galder Zamarreno</a>
 */
@CacheListener
public class PojoCacheGUI extends JBossCacheGUI
{
   public PojoCacheGUI(CacheModelDelegate cacheDelegate, boolean useConsole)
         throws Exception
   {
      super(cacheDelegate, useConsole);
   }

   @Override
   protected String getWelcomeMessage()
   {
      return "Welcome to the BeanShell console.\n\n" +
             "This console gives you a direct shell interface to the GUI above and allows you to manipulate the pojo cache directly. " +
             "Some of the variables initialised in this shell session are:\n\n" +
             "// an instance of org.jboss.cache.pojo\n" +
             "    PojoCache cache;\n" +
             "// the transaction manager registered with the cache\n" +
             "    TransactionManager transactionManager;\n";
   }

   @Override
   protected void configureInterpreter(Interpreter interpreter, CacheModelDelegate cacheDelegate) throws EvalError
   {
      interpreter.getNameSpace().importPackage("org.jboss.cache");
      interpreter.getNameSpace().importPackage("org.jboss.cache.pojo");
      interpreter.getNameSpace().importPackage("org.jboss.cache.transaction");
      interpreter.getNameSpace().importPackage("org.jboss.cache.pojo.test");
      interpreter.set("cache", cacheDelegate.getCacheShellVariable());
      interpreter.set("transactionManager", cacheDelegate.getGenericCache().getConfiguration().getRuntimeConfig().getTransactionManager());
   }

   @Override
   protected void populateTable(Map data)
   {
      Object key;
      Object val;
      int num_rows;
      clearTable();
      if (data == null) return;
      num_rows = data.size();

      if (num_rows > 0)
      {
         // sort this according to the natural sort order of keys
         TreeMap<Object, Object> sortedMap = new TreeMap<Object, Object>(data);

         for (Map.Entry<Object, Object> entry : sortedMap.entrySet())
         {
            key = entry.getKey();
            val = entry.getValue();
            getTableModel().addRow(new Object[]{key, val});
         }
         getTableModel().fireTableRowsInserted(0, num_rows - 1);
         validate();
      }
   }
}
