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

import org.jboss.cache.CacheSPI;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.cache.NodeSPI;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.EvictionConfig;
import org.jboss.cache.config.EvictionRegionConfig;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.lock.IsolationLevel;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.List;
import java.util.ArrayList;

/**
 * @author Daniel Huang
 * @version $Revison: $
 */
@Test(groups = {"functional"})
public class ElementSizePolicyTest
{
   CacheSPI<Object, Object> cache;
   int wakeupIntervalMillis = 0;
   final String ROOT_STR = "/test";
   Throwable t1_ex, t2_ex;
   final long DURATION = 10000;
   boolean isTrue;

   @BeforeMethod(alwaysRun = true)
   public void setUp() throws Exception
   {
      initCaches();
      wakeupIntervalMillis = cache.getConfiguration().getEvictionConfig().getWakeupIntervalSeconds() * 1000;
      log("wakeupInterval is " + wakeupIntervalMillis);
      if (wakeupIntervalMillis < 0)
      {
         fail("testEviction(): eviction thread wake up interval is illegal " + wakeupIntervalMillis);
      }

      t1_ex = t2_ex = null;
      isTrue = true;
   }

   void initCaches() throws Exception
   {
      Configuration conf = UnitTestCacheConfigurationFactory.createConfiguration(Configuration.CacheMode.LOCAL, true);
      EvictionConfig evConfig = conf.getEvictionConfig();
      evConfig.setDefaultEvictionPolicyClass("org.jboss.cache.eviction.ElementSizePolicy");
      evConfig.setWakeupIntervalSeconds(3);
      evConfig.setDefaultEventQueueSize(200000);

      List<EvictionRegionConfig> regionConfigs = new ArrayList<EvictionRegionConfig>();
      regionConfigs.add(createEvictionRegionConfig("_default_", 5000, 100));
      regionConfigs.add(createEvictionRegionConfig("/org/jboss/data", 10, 20));
      regionConfigs.add(createEvictionRegionConfig("/org/jboss/test/data", -1, 5));
      regionConfigs.add(createEvictionRegionConfig("/test/", 5000, 1));

      evConfig.setEvictionRegionConfigs(regionConfigs);

      cache = (CacheSPI<Object, Object>) new DefaultCacheFactory().createCache(conf, false);
      cache.getConfiguration().setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
      cache.getConfiguration().setIsolationLevel(IsolationLevel.SERIALIZABLE);
      cache.start();
   }

   private EvictionRegionConfig createEvictionRegionConfig(String regionName, int maxNodes, int maxElementsPerNode)
   {
      EvictionRegionConfig ercDefault = new EvictionRegionConfig();
      ercDefault.setRegionName(regionName);
      ElementSizeConfiguration esConfig = new ElementSizeConfiguration();
      if (maxNodes >= 0) esConfig.setMaxNodes(maxNodes);
      if (maxElementsPerNode >= 0) esConfig.setMaxElementsPerNode(maxElementsPerNode);
      ercDefault.setEvictionPolicyConfig(esConfig);
      return ercDefault;
   }

   @AfterMethod(alwaysRun = true)
   public void tearDown() throws Exception
   {
      cache.stop();
   }

   public void testEviction() throws Exception
   {
      String rootStr = "/org/jboss/test/data/";
      for (int i = 0; i < 10; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);
         try
         {
            cache.put(fqn, str, str);
            if (i % 2 == 0)
            {
               for (int k = 0; k < i; k++)
               {
                  cache.put(fqn, k, Integer.toString(k));
               }
            }
         }
         catch (Exception e)
         {
            fail("Failed to insert data" + e);
            e.printStackTrace();
         }
      }

      System.out.println(cache);
      _sleep(wakeupIntervalMillis + 500);
      System.out.println(cache);

      for (int i = 0; i < 10; i++)
      {
         Node node = cache.getNode("/org/jboss/test/data/" + Integer.toString(i));
         System.out.println(node);
         if (i % 2 == 0)
         {
            if (i < 6)
            {
               int numElements = ((NodeSPI) node).getDataDirect().size();
               assertEquals(i + 1, numElements);
            }
            else
            {
               assertNull(node);
            }
         }
         else
         {
            assertEquals(1, ((NodeSPI) node).getDataDirect().size());
         }
      }
   }

   public void testEviction2() throws Exception
   {
      String rootStr = "/org/jboss/data/";
      for (int i = 0; i < 20; i++)
      {
         String str = rootStr + Integer.toString(i);
         Fqn fqn = Fqn.fromString(str);
         cache.put(fqn, i, str);
         for (int k = 0; k < i; k++)
         {
            cache.put(fqn, k, str);
         }
      }

      _sleep(wakeupIntervalMillis + 500);

      for (int i = 0; i < 20; i++)
      {
         String str = rootStr + Integer.toString(i);
         Fqn fqn = Fqn.fromString(str);
         Node node = cache.getNode(fqn);
         System.out.println(i + " " + node);
         if (i > 9)
         {
            assertNull("Testing at " + i, node);
         }
         else
         {
            assertEquals(1 + i, node.getData().size());
         }
      }

      for (int i = 0; i < 17; i++)
      {
         cache.put("/org/jboss/data/" + Integer.toString(3), 100 + i, "value");
      }

      Node node = cache.getNode("/org/jboss/data/" + Integer.toString(3));
      assertEquals(21, node.getData().size());
      _sleep(wakeupIntervalMillis + 500);

      assertNull(cache.getNode("/org/jboss/data/" + Integer.toString(3)));
   }

   class MyPutter extends Thread
   {
      public MyPutter(String name)
      {
         super(name);
      }

      public void run()
      {
         int i = 0;
         final String myName = ROOT_STR + "/test1/node" + getName();
         while (isTrue)
         {
            try
            {
               cache.put(myName + i++, "value", i);
               sleep(1);
            }
            catch (Throwable e)
            {
               e.printStackTrace();
               if (t1_ex == null)
               {
                  t1_ex = e;
               }
            }
         }
      }
   }


   public void testConcurrentPutAndEvict() throws Exception
   {
      cache.stop();
      cache.destroy();
      cache.getConfiguration().setIsolationLevel(IsolationLevel.REPEATABLE_READ);

      cache.start();
      cache.put(ROOT_STR + "/concurrentPutAndEvict", "value", 1);

      for (int i = 0; i < 10; i++)
      {
         new MyPutter("Putter" + i).start();
      }

      int counter = 0;
      while (true)
      {
         counter++;
         if (t1_ex != null)
         {
            fail("Exception generated in put() " + t1_ex);
         }
         log("nodes/locks: " + cache.getNumberOfNodes() + "/" + cache.getNumberOfLocksHeld());
         _sleep(1000);
         if (counter > 10)
         {// run for 10 seconds
            isTrue = false;
            break;
         }
      }
   }

   private void _sleep(long msecs)
   {
      try
      {
         Thread.sleep(msecs);
      }
      catch (InterruptedException e)
      {
         e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
      }
   }

   private void log(String msg)
   {
      System.out.println("-- " + msg);
   }
}
