package org.apache.maven.hibernate.beans;

/* ====================================================================
 *   Copyright 2001-2004 The Apache Software Foundation.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * ====================================================================
 */

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.4 2004/04/25 02:29:43 brett 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 String delimiter = 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;
   }
   
   /**
    * @return
    */
   public String getDelimiter() 
   {
      return delimiter;
   }

   /**
    * @param string
    */
   public void setDelimiter(String string) 
   {
      delimiter = 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, getClass().getClassLoader());
         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());
      schemaExport.setDelimiter(getDelimiter());
      return schemaExport;
   }
}
