/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.loader;

import org.jboss.cache.CacheSPI;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.transaction.DummyTransactionManager;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

@Test(groups = "functional")
public class DataSourceIntegrationTest extends AbstractCacheLoaderTestBase
{
   private String old_factory = null;
   private final String FACTORY = "org.jboss.cache.transaction.DummyContextFactory";
   private final String JNDI_NAME = "java:/MockDS";
   private CacheSPI cache;

   @BeforeMethod(alwaysRun = true)
   public void setUp() throws Exception
   {
      old_factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
      System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
      DummyTransactionManager.getInstance();
   }

   protected CacheLoaderConfig getCacheLoaderConfig(String jndi) throws Exception
   {
      String props = "cache.jdbc.datasource=" + jndi + "\ncache.jdbc.table.create=true\ncache.jdbc.table.drop=true";
      CacheLoaderConfig cacheLoaderConfig = getSingleCacheLoaderConfig("", "org.jboss.cache.loader.JDBCCacheLoader", props, false, false, false);
      return cacheLoaderConfig;
   }

   /**
    * Tests fix for JBCACHE-303, ensuring that JDBCCacheLoader works if
    * its DataSource is not in JNDI until start is called.
    *
    * @throws Exception
    */
   public void testDataSourceIntegration() throws Exception
   {
      Context context = new InitialContext();
      try
      {
         Object obj = context.lookup(JNDI_NAME);
         assertNull(JNDI_NAME + " not bound", obj);
      }
      catch (NameNotFoundException n)
      {
         // expected
      }
      cache = (CacheSPI) new DefaultCacheFactory().createCache(false);
      cache.getConfiguration().setCacheMode("local");
      cache.getConfiguration().setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
      cache.getConfiguration().setCacheLoaderConfig(getCacheLoaderConfig(JNDI_NAME));
      cache.create();


      context.bind(JNDI_NAME, new MockDataSource());
      assertNotNull(JNDI_NAME + " bound", context.lookup(JNDI_NAME));
      cache.start();

      assertNotNull("Cache has a cache loader", cache.getCacheLoaderManager().getCacheLoader());
   }

   @AfterMethod(alwaysRun = true)
   public void tearDown() throws Exception
   {
      Context ctx = new InitialContext();
      ctx.unbind(JNDI_NAME);
      if (old_factory != null)
      {
         System.setProperty(Context.INITIAL_CONTEXT_FACTORY, old_factory);
      }
      else
      {
         System.getProperties().remove(Context.INITIAL_CONTEXT_FACTORY);
      }


      if (cache != null)
      {
         cache.stop();
         cache.destroy();
      }
   }

   private static class MockDataSource implements DataSource
   {
      private String userName;
      private String jdbcUrl;
      private String jdbcPassword;

      public MockDataSource()
      {
         Properties properties = new Properties();
         try
         {
            properties.load(this.getClass().getClassLoader().getResourceAsStream("cache-jdbc.properties"));
            Class.forName(properties.getProperty("cache.jdbc.driver"));
         }
         catch (Exception e)
         {
            throw new IllegalStateException("Error loading jdbc properties ", e);
         }
         userName = properties.getProperty("cache.jdbc.user");
         jdbcUrl = properties.getProperty("cache.jdbc.url");
         jdbcPassword = properties.getProperty("cache.jdbc.password");
      }

      public Connection getConnection() throws SQLException
      {
         return DriverManager.getConnection(jdbcUrl, userName, jdbcPassword);
      }

      public Connection getConnection(String user, String password) throws SQLException
      {
         return DriverManager.getConnection(jdbcUrl, userName, jdbcPassword);
      }

      public int getLoginTimeout() throws SQLException
      {
         return 0;
      }

      public PrintWriter getLogWriter() throws SQLException
      {
         return null;
      }

      public void setLoginTimeout(int seconds) throws SQLException
      {
      }

      public void setLogWriter(PrintWriter printWriter) throws SQLException
      {
      }

      // preliminary JDK6 support - just so it compiles!!!
      public boolean isWrapperFor(Class<?> ifc)
      {
         return false;
      }

      public <T> T unwrap(Class<T> iface)
      {
         return null;
      }
   }
}
