/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.soa.bpel.runtime.db;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.jboss.system.ServiceMBeanSupport;

/**
 * Initialize a given datasource
 *
 * Takes a list resources that are .sql files and checks to see if they have alrady been executed
 * on a given datasource by executing a sql query.  If the sql query fails, then the .sql files are executed.
 *
 * @author <a href="bill@jboss.com">Bill Burke</a>
 * @version $Revision: 1.1 $
 */
public class DatabaseInitializer extends ServiceMBeanSupport implements DatabaseInitializerMBean
{
   private String datasource;
   private String sqlFiles;
   private String existsSql;
   private boolean useEOL ;


   public String getExistsSql()
   {
      return existsSql;
   }

   public void setExistsSql(String existsSql)
   {
      this.existsSql = existsSql;
   }

   public boolean getUseEOL()
   {
      return useEOL;
   }

   public void setUseEOL(boolean useEOL)
   {
      this.useEOL = useEOL;
   }

   public String getSqlFiles()
   {
      return sqlFiles;
   }

   public void setSqlFiles(String sqlFiles)
   {
      this.sqlFiles = sqlFiles;
   }

   public String getDatasource()
   {
      return datasource;
   }

   public void setDatasource(String datasource)
   {
      this.datasource = datasource;
   }

   protected void initDatabase() throws Exception
   {
      DataSource ds = (DataSource)new InitialContext().lookup(datasource);
      Connection conn = ds.getConnection();
      boolean load = false;

      Statement st = conn.createStatement();
      ResultSet rs = null;
      try
      {
         rs = st.executeQuery(existsSql.trim());
         rs.close();
      }
      catch (SQLException e)
      {
         load = true;
      }
      st.close();
      if (!load)
      {
         log.info(datasource + " datasource is already initialized");
         return;
      }

      log.info("Initializing " + datasource + " from listed sql files");

      String[] list = sqlFiles.split(",");
      for (String sql : list)
      {
         executeSql(sql.trim(), conn);
      }
   }

   public void executeSql(String resource, Connection conn)
   {
     UserTransaction tx =null;
     try
     {
       tx =  (UserTransaction)new InitialContext().lookup("UserTransaction");
       tx.begin();
       
       log.debug("Execute SQL from resource: "+resource);

       URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
       
       log.debug("Execute SQL from resource URL: "+url);
       
       String sql = getStringFromStream(url.openStream());
       sql = sql.replaceAll("(?m)^--([^\n]+)?$", ""); // Remove all commented lines
       final String[] statements ;
       if (useEOL) {
           statements = sql.split("[\n;]");
       } else {
           statements = sql.split(";");
       }
       for (String statement : statements)
       {
         if ((statement == null) || ("".equals(statement.trim()))) {
         }
         else {
            Statement sqlStatement = conn.createStatement();
            try
            {
               sqlStatement.executeUpdate(statement);
            }
            finally
            {
               sqlStatement.close();
            }
         }
       }

       tx.commit();
     }
     catch (Throwable t) 
     {
       if(tx!=null)
         try {
           tx.rollback();
         } catch (SystemException e) {
           // 
         }
       throw new RuntimeException("Failed to create database", t);
     }
   }


   @Override
   protected void startService() throws Exception
   {
      initDatabase();
      super.startService();
   }
   
   private String getStringFromStream(InputStream is) throws Exception
   {
	   byte[] bytes = readStream(is);
	   return new String(bytes, "UTF-8");
	      
   }
   
   /**
	 * Read the supplied InputStream and return as an array of bytes.
	 * @param stream The stream to read.
	 * @return The stream contents in an array of bytes.
	 */
	public static byte[] readStream(InputStream stream) {
		if(stream == null) {
			throw new IllegalArgumentException("null 'stream' arg passed in method call.");
		}
		
		ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
		byte[] buffer = new byte[256];
		int readCount = 0;
		
		try {
			while((readCount = stream.read(buffer)) != -1) {
				outBuffer.write(buffer, 0, readCount);
			}
		} catch (IOException e) {
			throw new IllegalStateException("Error reading stream.", e);
		}		
		
		return outBuffer.toByteArray();
	}
}
