package org.jboss.cache.loader;

import org.jboss.cache.CacheSPI;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.Configuration.CacheMode;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

@Test(groups = "functional")
public class PreloadTest extends AbstractCacheLoaderTestBase
{
   CacheSPI<Object, Object> cache;
   Fqn fqn = Fqn.fromString("/a/b/c");
   Object key = "key", value = "value";

   @AfterMethod
   public void tearDown()
   {
      if (cache != null) TestingUtil.killCaches(cache);
   }

   public void testPreload() throws Exception
   {
      Configuration c = UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.LOCAL);
      c.setCacheLoaderConfig(getSingleCacheLoaderConfig("/a", DummySharedInMemoryCacheLoader.class.getName(), "", false, false, false));
      cache = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(c.clone());
      cache.put(fqn, key, value);
      assertExists();

      cache.destroy();

      cache = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(c.clone());
      assertExists();
   }

   public void testPreloadMultiRegions() throws Exception
   {
      Configuration c = UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.LOCAL);
      c.setCacheLoaderConfig(getSingleCacheLoaderConfig("/a", DummySharedInMemoryCacheLoader.class.getName(), "", false, false, false));
      cache = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(c.clone());
      cache.put(fqn, key, value);
      assertExists();

      cache.destroy();

      c.setCacheLoaderConfig(getSingleCacheLoaderConfig("/c,/a,/b", DummySharedInMemoryCacheLoader.class.getName(), "", false, false, false));
      cache = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(c.clone());
      assertExists();

      c.setCacheLoaderConfig(getSingleCacheLoaderConfig("/c, /a, /b", DummySharedInMemoryCacheLoader.class.getName(), "", false, false, false));
      cache = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(c.clone());
      assertExists();

      c.setCacheLoaderConfig(getSingleCacheLoaderConfig("  /c,   /a,   /b", DummySharedInMemoryCacheLoader.class.getName(), "", false, false, false));
      cache = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(c.clone());
      assertExists();
   }

   private void assertExists() throws Exception
   {
      CacheLoader loader = cache.getCacheLoaderManager().getCacheLoader();
      assert loader.get(fqn).get(key).equals(value);
      assert cache.peek(fqn, false).getDataDirect().get(key).equals(value);
   }
}
