/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.cache.pojo.rollback;

import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;

import javax.transaction.TransactionManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.aop.Advised;
import org.jboss.aop.advice.Interceptor;
import org.jboss.cache.pojo.PojoCache;
import org.jboss.cache.pojo.PojoCacheFactory;
import org.jboss.cache.pojo.interceptors.PojoFailedTxMockupInterceptor;
import org.jboss.cache.pojo.interceptors.dynamic.CacheFieldInterceptor;
import org.jboss.cache.pojo.test.Person;
import org.jboss.cache.transaction.DummyTransactionManager;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * Additional basic tests
 *
 * @author Ben Wang
 */

@Test(groups = {"functional"})
public class LocalUndoTest
{
   Log log_ = LogFactory.getLog(LocalUndoTest.class);
   PojoCache cache_;
   TransactionManager tx_mgr;


   @BeforeMethod(alwaysRun = true)
   protected void setUp() throws Exception
   {
      log_.info("setUp() ....");
      String configFile = "META-INF/local-service.xml";
      boolean toStart = false;
      cache_ = PojoCacheFactory.createCache(configFile, toStart);
      cache_.start();
      tx_mgr = DummyTransactionManager.getInstance();

   }

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

//   public void testDummy() {}

   private void setTxRollback(boolean isTrue)
   {
      PojoFailedTxMockupInterceptor.TX_ROLLBACK = isTrue;
   }

   public void testSimpleTxWithRollback1() throws Exception
   {
      log_.info("testSimpleTxWithRollback1() ....");
      Person test = new Person();
      test.setName("Ben");
      test.setAge(10);

      setTxRollback(true);
      try
      {
    	  cache_.attach("/a", test);
      }
      catch (Exception e)
      {
      }
      assertFalse("Should not have cache interceptor ", hasCacheInterceptor(test));
   }

   private boolean hasCacheInterceptor(Object pojo)
   {
      Interceptor[] interceptors = ((Advised) pojo)._getInstanceAdvisor().getInterceptors();
      for (int i = 0; i < interceptors.length; i++)
      {
         if (interceptors[i] instanceof CacheFieldInterceptor)
            return true;
      }
      return false;
   }

   public void testSimpleTxWithRollback2() throws Exception
   {
      log_.info("testSimpleTxWithRollback1() ....");
      Person test = new Person();
      test.setName("Ben");
      test.setAge(10);
      cache_.attach("/a", test);

      setTxRollback(true);
      try
      {
         cache_.detach("/a");
      }
      catch (Exception e)
      {
      }

      assertTrue("Should still have cache interceptor ", hasCacheInterceptor(test));
   }




}
