package org.jboss.cache.pojo;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.fail;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.config.Configuration.CacheMode;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
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;

/**
 */

@Test(groups = {"functional"})
public class ReplicatedTxTest 
{
   Log log = LogFactory.getLog(ReplicatedTxTest.class);
   PojoCache cache, cache1;
   final String FACTORY = "org.jboss.cache.transaction.DummyContextFactory";
   DummyTransactionManager tx_mgr;
   Throwable t1_ex, t2_ex;
   long start = 0;



   @BeforeMethod(alwaysRun = true)
   protected void setUp() throws Exception
   {
      log.info("setUp() ....");
      boolean toStart = false;
      cache = PojoCacheFactory.createCache(UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.REPL_SYNC), toStart);
      cache.start();
      cache1 = PojoCacheFactory.createCache(UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.REPL_SYNC), toStart);
      cache1.start();

      System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);

      tx_mgr = DummyTransactionManager.getInstance();
      t1_ex = t2_ex = null;
   }

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

      DummyTransactionManager.destroy();
   }

//   public void testDummy() {}

   UserTransaction getTransaction() throws SystemException, NotSupportedException, NamingException
   {
      Properties prop = new Properties();
      prop.put(Context.INITIAL_CONTEXT_FACTORY,
              "org.jboss.cache.transaction.DummyContextFactory");
      return (UserTransaction) new InitialContext(prop).lookup("UserTransaction");
   }

   private Person createPerson(String id, String name, int age)
   {
      Person p = new Person();
      p.setName(name);
      p.setAge(age);
      cache.attach(id, p);
      return p;
   }

   public void testSimple() throws Exception
   {
      log.info("testSimple() ....");
      UserTransaction tx = getTransaction();
      tx.begin();
      Person p = createPerson("/person/test1", "Harald Gliebe", 32);
      tx.commit();
      tx.begin();
      p.setName("Benoit");
      tx.commit();
      Person p1 = (Person) cache1.find("/person/test1");
      assertEquals("Benoit", p.getName());
      assertEquals("Benoit", p1.getName());
      tx.begin();
      p1.setAge(61);
      tx.commit();
      assertEquals(61, p.getAge());
      assertEquals(61, p1.getAge());
   }

   public void testModification() throws Exception
   {
      UserTransaction tx = getTransaction();
      tx.begin();
      Person p = createPerson("/person/test2", "Harald", 32);
      p.setName("Harald Gliebe");
      tx.commit();
      Person p1 = (Person) cache1.find("/person/test2");
      tx.begin();
      p1.setName("Benoit");
      tx.commit();
      assertEquals(p.getName(), "Benoit");
      assertEquals(p1.getName(), "Benoit");
      tx.begin();
      p1.setName("Harald");
      tx.rollback();
      assertEquals(p.getName(), "Benoit");
      assertEquals(p1.getName(), "Benoit");
   }

   public void testConcurrentPuts() throws Exception
   {
      Thread t1 = new Thread()
      {
         public void run()
         {
            try
            {
               List<String> lang = ((Person) cache.find("/person/test6")).getLanguages();
               UserTransaction tx = getTransaction();
               tx.begin();
               lang.add("German");
               TestingUtil.sleepThread(17000);
               tx.commit();
            }
            catch (RollbackException rollback)
            {
               ;
            }
            catch (Exception ex)
            {
               t1_ex = ex;
            }
         }
      };

      Thread t2 = new Thread()
      {
         public void run()
         {
            UserTransaction tx = null;
            try
            {
               TestingUtil.sleepThread(1000); // give Thread1 time to createPerson
               List<String> lang = ((Person) cache.find("/person/test6")).getLanguages();
               tx = getTransaction();
               tx.begin();
               lang.add("English");
               tx.commit();
            }
            catch (RollbackException rollback)
            {
               ;
            }
            catch (Exception ex)
            {
               try
               {
                  tx.rollback();
               } catch (SystemException e)
               {
                  e.printStackTrace();
                  t2_ex = e;
               }
            }
         }
      };

      Person p = createPerson("/person/test6", "p6", 50);
      List<String> lang = new ArrayList<String>();
      lang.add("German");
      p.setLanguages(lang);

      t1.start();
      t2.start();

      t1.join();
      t2.join();

      // t2 should rollback due to timeout while t2 should succeed
      if (t2_ex != null)
         fail("Thread1 failed: " + t2_ex);
      if (t1_ex != null)
         fail("Thread2 failed: " + t1_ex);

      int size = ((Person) cache.find("/person/test6")).getLanguages().size();
      assertEquals("number of languages should be 2, but is " + size + " (" +
              ((Person) cache.find("/person/test6")).getLanguages().size() + ")",
              2, size);
      size = ((Person) cache1.find("/person/test6")).getLanguages().size();
      assertEquals("number of languages should be 2, but is " + size + " (" +
              ((Person) cache.find("/person/test6")).getLanguages().size() + ")",
              2, size);
   }

   void log(String s)
   {
      long now;
      if (start == 0)
         start = System.currentTimeMillis();
      now = System.currentTimeMillis();

      System.out.println("[" + Thread.currentThread().getName() + "] [" + (now - start) + "] " + s);
   }





}

