/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache MavenSession" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache MavenSession", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * ====================================================================
 */
package org.apache.maven.hibernate.beans;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;

import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.DirectoryScanner;

/**
 * 
 * The Bean which serves as Proxy To Hibernate API
 * <br/>
 * 
 * 
 *   
 * @author <a href="michal.maczka@dimatics.com">Michal Maczka</a> 
 * @version $Id: SchemaExportBean.java,v 1.1 2003/05/15 13:06:27 michal Exp $
 */
public class SchemaExportBean
{

   private String includes = null;
   private String excludes = null;
   private String basedir = null;
   private String properties = null;
   private String config = null;
   private String outputFile = null;
   private boolean quiet = false;
   private boolean text = false;
   private boolean drop = false;

   /**
    * @return
    */
   public String getIncludes()
   {
      return includes;
   }

   /**
    * @return
    */
   public String getOutputFile()
   {
      return outputFile;
   }

   /**
    * @return
    */
   public boolean getQuiet()
   {
      return quiet;
   }

   /**
    * @return
    */
   public boolean getText()
   {
      return text;
   }

   /**
    * @param string
    */
   public void setIncludes(String string)
   {
      includes = string;
   }

   /**
    * @param string
    */
   public void setOutputFile(String string)
   {
      outputFile = string;
   }

   /**
    * @param b
    */
   public void setQuiet(boolean b)
   {
      quiet = b;
   }

   /**
    * @param b
    */
   public void setText(boolean b)
   {
      text = b;
   }

   /**
    * @return
    */
   public String getConfig()
   {
      return config;
   }

   /**
    * @return
    */
   public String getProperties()
   {
      return properties;
   }

   /**
    * @param string
    */
   public void setConfig(String string)
   {
      config = string;
   }

   /**
    * @param string
    */
   public void setProperties(String string)
   {
      properties = string;
   }

   /**
    * @return
    */
   public String getBasedir()
   {
      return basedir;
   }

   /**
    * @return
    */
   public boolean isDrop()
   {
      return drop;
   }

   /**
    * @return
    */
   public String getExcludes()
   {
      return excludes;
   }

   /**
    * @param string
    */
   public void setBasedir(String string)
   {
      basedir = string;
   }

   /**
    * @param b
    */
   public void setDrop(boolean b)
   {
      drop = b;
   }

   /**
    * @param string
    */
   public void setExcludes(String string)
   {
      excludes = string;
   }

   /**
    * 
    * Hibernate requires that 
    * Java classes (beans) are accesible on the
    * classpath. As they are not in plugin classpath
    * we have to take care about. 
    * To assure that we have them visible for plugin
    * classloader
    * we will make temporay change to context classloader
    * which will be restored when method terminates.
    * 
    */
   public void execute() throws Exception
   {

      Thread currentThread = Thread.currentThread();
      ClassLoader oldClassLoader = currentThread.getContextClassLoader();
      try
      {

         File baseDirFile = new File(getBasedir());
         URL[] urls = { baseDirFile.toURL()};
         System.out.println(urls[0]);
         URLClassLoader newClassLoader =
            new URLClassLoader(urls, oldClassLoader);
         currentThread.setContextClassLoader(newClassLoader);
         Configuration cfg = getConfiguration();
         SchemaExport schemaExport = getSchemaExport(cfg);

         if (isDrop())
         {
            schemaExport.drop(!getQuiet(), !getText());
         }
         else
         {
            schemaExport.create(!getQuiet(), !getText());
         }
      }
      finally
      {
         currentThread.setContextClassLoader(oldClassLoader);
      }
   }

   /**
    * Builds list of files for which will be included 
    * in the schema. Uses ANT file scanner.    
    */
   private String[] getFiles()
   {

      List files = new LinkedList();

      DirectoryScanner directoryScanner = new DirectoryScanner();
      directoryScanner.setBasedir(getBasedir());

      System.out.println("Excludes:" + getExcludes());
      System.out.println("Includes:" + getIncludes());
      System.out.println("Base dir:" + getBasedir());

      directoryScanner.setExcludes(StringUtils.split(getExcludes(), ","));
      directoryScanner.setIncludes(StringUtils.split(getIncludes(), ","));

      directoryScanner.scan();
      String[] includesFiles = directoryScanner.getIncludedFiles();
      for (int i = 0; i < includesFiles.length; i++)
      {
         File file = new File(includesFiles[i]);
         if (!file.isFile())
         {
            file = new File(directoryScanner.getBasedir(), includesFiles[i]);
         }
         files.add(file.getAbsolutePath());
      }
      String[] retValue = (String[]) files.toArray(new String[0]);
      return retValue;
   }

   /**
    * 
    */
   private Configuration getConfiguration() throws HibernateException
   {
      Configuration cfg = new Configuration();
      if (getConfig() != null)
      {
         cfg.configure(getConfig());
      }

      String[] files = getFiles();
      for (int i = 0; i < files.length; i++)
      {
         String filename = files[i];
         if (filename.endsWith(".jar"))
         {
            cfg.addJar(filename);
         }
         else
         {
            cfg.addFile(filename);
         }
      }
      return cfg;
   }

   private SchemaExport getSchemaExport(Configuration cfg)
      throws HibernateException, IOException
   {
      SchemaExport schemaExport = null;
      if (getProperties() == null)
      {
         schemaExport = new SchemaExport(cfg);
      }
      else
      {
         Properties properties = new Properties();
         properties.load(new FileInputStream(getProperties()));
         schemaExport = new SchemaExport(cfg, properties);
      }
      System.out.println("Output file:" + getOutputFile());
      schemaExport.setOutputFile(getOutputFile());
      return schemaExport;
   }

}
