package org.jboss.cache.buddyreplication;

import org.jboss.cache.CacheSPI;
import org.jboss.cache.Fqn;
import org.jboss.cache.util.TestingUtil;
import org.jboss.cache.util.CachePrinter;
import org.testng.annotations.Test;

/**
 * This is to test JBCACHE-1229
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.1.0
 */
@Test(groups = "functional")
public class DisabledStateTransferTest extends BuddyReplicationTestsBase
{
   public void testCachesWithoutStateTransfer() throws Exception
   {
      caches = createCaches(1, 3, false, false, false, false);

      int cacheNumber = 0;
      for (CacheSPI c : caches)
      {
         c.getConfiguration().setFetchInMemoryState(false);
         c.start();
         c.put("/" + cacheNumber++, "k", "v");
      }

      TestingUtil.blockUntilViewsReceived(caches.toArray(new CacheSPI[0]), 60000);

      for (CacheSPI c : caches)
         System.out.println("Cache (local address " + c.getLocalAddress() + ") contents: " + CachePrinter.printCacheLockingInfo(c));

      for (int i = 0; i < 3; i++)
      {
         int backupIndex = i == 2 ? 0 : i + 1;

         assert caches.get(i).exists("/" + i) : "Data should exist on owner (cache #" + i + ")";
         Fqn backup = fqnTransformer.getBackupFqn(caches.get(i).getLocalAddress(), Fqn.fromString("/" + i));

         assert caches.get(backupIndex).exists(backup.getParent()) : "Backup region should have been created on buddy (cache #" + backupIndex + ")";
         boolean backupStatePropagated = caches.get(backupIndex).exists(backup);
         boolean backupOlderThanOwner = backupIndex < i;
         assert (!backupStatePropagated && !backupOlderThanOwner) || (backupStatePropagated && backupOlderThanOwner) : "Backup state should NOT have been transferred to buddy (cache #" + backupIndex + ")";
      }

      // now NEW state should transfer just fine.

      cacheNumber = 0;
      for (CacheSPI c : caches)
      {
         c.put("/" + (cacheNumber++) + "_NEW", "k", "v");
      }

      for (int i = 0; i < 3; i++)
      {
         int backupIndex = i == 2 ? 0 : i + 1;

         assert caches.get(i).exists("/" + i + "_NEW") : "Data should exist on owner (cache #" + i + ")";
         Fqn backup = fqnTransformer.getBackupFqn(caches.get(i).getLocalAddress(), Fqn.fromString("/" + i + "_NEW"));

         assert caches.get(backupIndex).exists(backup.getParent()) : "Backup region should have been created on buddy (cache #" + backupIndex + ")";
         assert caches.get(backupIndex).exists(backup) : "Backup state should NOT have been transferred to buddy (cache #" + backupIndex + ")";
      }
   }
}
