package org.jboss.cache.multiplexer;

import org.jboss.cache.Cache;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.RuntimeConfig;
import org.jgroups.Channel;
import org.jgroups.JChannel;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * Tests that JBC prefers an injected Channel to creating one via
 * a configured JChannelFactory and stack name.
 *
 * @author <a href="brian.stansberry@jboss.com">Brian Stansberry</a>
 * @version $Revision: 4880 $
 */
@Test(groups = {"functional", "jgroups"}, enabled = true)
public class ChannelInjectionPreferenceTest
{
   private MultiplexerTestHelper muxHelper;
   private Cache cache;
   private boolean cacheStarted;

   @BeforeMethod(alwaysRun = true)
   public void setUp() throws Exception
   {
      muxHelper = new MultiplexerTestHelper();
      Configuration config = new Configuration();
      config.setCacheMode(Configuration.CacheMode.REPL_SYNC);
      config.setClusterConfig(JChannel.DEFAULT_PROTOCOL_STACK);
      cache = new DefaultCacheFactory().createCache(config, false);
      cacheStarted = false;
   }

   @AfterMethod(alwaysRun = true)
   public void tearDown() throws Exception
   {
      try
      {
         if (cacheStarted && cache != null)
         {
            cache.stop();
            cache.destroy();
         }
      }
      finally
      {
         if (muxHelper != null)
         {
            muxHelper.tearDown();
            muxHelper = null;
         }
      }
   }

   public void testChannelInjectionPreference() throws Exception
   {
      muxHelper.configureCacheForMux(cache);

      Channel channel = new JChannel(JChannel.DEFAULT_PROTOCOL_STACK);

      RuntimeConfig rtcfg = cache.getConfiguration().getRuntimeConfig();
      rtcfg.setChannel(channel);

      // Start shouldn't fail and we shouldn't be using mulitplexer
      checkStart(false, false);

      assertEquals("Injected channel used", channel, rtcfg.getChannel());
   }

   private void checkStart(boolean expectFail, boolean expectMux)
   {
      try
      {
         cache.start();
         cacheStarted = true;
         if (expectFail)
         {
            fail("Start did not fail as expected");
         }

         if (expectMux)
         {
            assertTrue("Cache is using mux", cache.getConfiguration().isUsingMultiplexer());
         }
         else
         {
            assertFalse("Cache is not using mux ", cache.getConfiguration().isUsingMultiplexer());
         }
      }
      catch (Exception e)
      {
         if (!expectFail)
         {
            fail("Caught exception starting cache " + e.getLocalizedMessage());
         }
      }

   }
}
