package org.jboss.cache.pojo.collection;

import static org.testng.AssertJUnit.fail;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.config.Configuration.CacheMode;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.pojo.PojoCache;
import org.jboss.cache.pojo.PojoCacheFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * List implementation testing.
 *
 * @author Ben Wang
 */

@Test(groups = {"functional"})
public class CachedListImplTest 
{
   Log log = LogFactory.getLog(CachedListImplTest.class);
   PojoCache cache_, cache1_;

   @BeforeMethod(alwaysRun = true)
   protected void setUp() throws Exception
   {
      log.info("setUp() ....");
      boolean toStart = false;
      cache_ = PojoCacheFactory.createCache(UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.REPL_SYNC), toStart);
      cache_.getCache().getConfiguration().setFetchInMemoryState(false);
      cache1_ = PojoCacheFactory.createCache(UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.REPL_SYNC), toStart);
      cache1_.getCache().getConfiguration().setFetchInMemoryState(false);
      cache_.start();
      cache1_.start();
   }

   @AfterMethod(alwaysRun = true)
   protected void tearDown() throws Exception
   {
      cache_.stop();
      cache1_.stop();
   }

   @SuppressWarnings("unchecked")
   public void testSimpleRepl()
   {
      List<String> list = new ArrayList<String>();
      list.add("1");
      list.add("2");

      cache_.attach("list", list);

      // proxy now
      list = (List<String>) cache_.find("list");

      // test repl
      try {
         cache_.getCache().put(Fqn.fromString("test"), "1", list);
         fail("Should have a non-serializable exception on list: " +list);
      } catch (Exception ex)
      {
         // OK. It works
      }

      // JBCACHE-975
      list = (List<String>) cache_.detach("list");

      // test repl
      cache_.getCache().put(Fqn.fromString("test"), "1", list);

      ArrayList<String> l1 = (ArrayList<String>) cache1_.getCache().get(Fqn.fromString("test"), "1");
      System.out.println(" list : " + l1);
   }
}

