package org.jboss.cache.optimistic;

import org.jboss.cache.TreeCache;
import org.jboss.cache.OptimisticTreeNode;
import org.jboss.cache.Fqn;
import org.jboss.cache.misc.TestingUtil;

import javax.transaction.TransactionManager;

/**
 * Tests removal of a node before the node is even created.
 */
public class RemoveBeforeCreateTest extends AbstractOptimisticTestCase
{
   TreeCache[] c = null;
   TransactionManager t;

   protected void setUp() throws Exception
   {
      c = new TreeCache[2];
      c[0] = createReplicatedCache(TreeCache.REPL_ASYNC);
      c[1] = createReplicatedCache(TreeCache.REPL_ASYNC);

      TestingUtil.blockUntilViewsReceived(c, 20000);

      t = c[0].getTransactionManager();
   }

   protected void tearDown()
   {
      if (c != null)
      {
         destroyCache(c[0]);
         destroyCache(c[1]);
         c = null;
      }
   }

   public RemoveBeforeCreateTest(String name)
   {
      super(name);
   }

   public void testControl() throws Exception
   {
      t.begin();
      c[0].put("/control", "key", "value");
      t.commit();

      // sleep to replicate - remember, this is repl_async
      TestingUtil.sleepThread(500);

      assertEquals("value", c[0].get("/control", "key"));
      assertEquals("value", c[1].get("/control", "key"));
      
      DefaultDataVersion v1 = (DefaultDataVersion) ((OptimisticTreeNode) c[0].get("/control")).getVersion();
      assertEquals(1, v1.getRawVersion());

      DefaultDataVersion v2 = (DefaultDataVersion) ((OptimisticTreeNode) c[1].get("/control")).getVersion();
      assertEquals(1, v2.getRawVersion());


   }

   public void testRemoveBeforePut() throws Exception
   {
      Fqn f = Fqn.fromString("/test");
      assertNull(c[0].get(f));
      assertNull(c[1].get(f));

      t.begin();
      c[0].remove(f);

      // should NOT barf!!!
      t.commit();

      assertNull(c[0].get(f));
      assertNull(c[1].get(f));
   }

}
