/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   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.

====================================================================== */

package org.bodington.ant;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.JDBCTask;
import org.bodington.installation.Installer;
import org.bodington.server.BuildingServer;

/**
 * An ANT task for creating an Bodington database.
 * <h3>Use</h3>
 * <p>
 * As this task is not a core ANT task, you will need to declare it in your
 * build file. You will need to add something such as the following (the nested
 * <code>classpath</code> element tells ANT where to find the task).
 * </p>
 * 
 * <pre>
 * 
 *   &lt;taskdef name=&quot;database-setup&quot; classname=&quot;org.bodington.ant.DatabaseSetupTask&quot;&gt;
 *     &lt;classpath&gt;
 *       &lt;pathelement location=&quot;${build}/bodserver.jar&quot;/&gt;
 *     &lt;/classpath&gt;
 *   &lt;/taskdef&gt;
 *   
 * </pre>
 * 
 * <h3>Parameters</h3>
 * <table cellspacing="0" border="1"> <thead>
 * <tr>
 * <th>Attribute</th>
 * <th>Description</th>
 * <th>Required</th>
 * </tr>
 * </thead> <tbody>
 * <tr>
 * <td>driver</td>
 * <td>The name of the JDBC driver.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>url</td>
 * <td>The URL to connection to the database with.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>userid</td>
 * <td>The userid to connect to the database as.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>password</td>
 * <td>The password to use connecting to the database.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>drop</td>
 * <td>If set to true then the all tables will be dropped before attempting to create replacements.</td>
 * <td>No[*]</td>
 * </tr>
 * <tr>
 * <td>create</td>
 * <td>If we should attempt to create new database tables.</td>
 * <td>No[*]</td>
 * </tr>
 * </tbody> </table>
 * [*] - One of these should be set or nothing will happen.
 * <h3>Examples</h3>
*
 * You can call the task (within a target) using the following entry:
 * 
 * <pre>
 * 
 *   &lt;database-setup driver=&quot;org.postgresql.Driver&quot;
 *   url=&quot;jdbc:postgresql://localhost/database&quot;
 *   userid=&quot;username&quot;
 *   password=&quot;password&quot;/&gt;
 *  
 * </pre>
 * @author buckett
 */

public class DatabaseSetupTask extends JDBCTask
{

    private String driver;
    private boolean drop;
    private boolean create;

    public void execute() throws BuildException
    {
        Connection conn = getConnection();
        try
        {
            if(isDrop())
            {
                Installer.deleteTables(conn);
            }
            if (isCreate())
            {
                Installer.createTables(conn, this.getClass(), null, Installer.getSQLSubstitutions(driver), false,
                    "", "");
            }
            conn.commit();
        }
        catch (SQLException e)
        {
            throw new BuildException(e);
        }
        catch (IOException ioe)
        {
            throw new BuildException(ioe);
        }
        finally
        {
            if (conn != null)
            {
                try
                {
                    conn.close();
                }
                catch (SQLException ingore)
                {
                }
            }
        }
      
        if (isCreate())
        {
            try
            {
                AntClassLoader loader = (AntClassLoader)getClass().getClassLoader();
                loader.setParent(getLoader());
                Installer.createMinimalData(getBodingtonProperties());
                BuildingServer.getInstance().shutdown();
            }
            catch (Exception e)
            {
                throw new BuildException(e);
            }
        }
    }

    /**
     * This gets a Properties object suitable for feeding to the BuildingServer.
     * It takes the options that were used to configure this ant task to
     * build the properties.
     * @return A Properties object.
     */
    private Properties getBodingtonProperties()
    {
        Properties props = new Properties();
        props.setProperty("buildingserver.job_scheduler.enabled", "no");
        props.put("sqldatabase.url", getUrl());
        props.put("sqldatabase.user_name", getUserId());
        props.put("sqldatabase.password", getPassword());
        props.put("sqldatabase.driver", getDriver());
        if (getDriver().equals("org.hsqldb.jdbcDriver"))
        {
            props.put("buildingserver.dbimplementation",
                "org.bodington.sqldatabase.EmbeddedHSqlDatabase");
        }
        return props;
    }

    /**
     * Gets the class that is used from the driver.
     * @return The name of the driver.
     */
    public String getDriver()
    {
        return this.driver;
    }
    
    /**
     * Sets the driver that will be used.
     * @param driver The driver to set.
     */
    public void setDriver(String driver)
    {
        this.driver = driver;
        super.setDriver(driver);
    }
    
    /**
     * Check if the old tables will be dropped first.
     * @return Returns true if the old tables should be dropped.
     */
    public boolean isDrop()
    {
        return drop;
    }
    
    /**
     * Set if the old tables should be dropped first.
     * @param drop If true is passed then the old tables will be dropped.
     */
    public void setDrop(boolean drop)
    {
        this.drop = drop;
    }

    /**
     * @return Returns the create.
     */
    public boolean isCreate()
    {
        return create;
    }

    /**
     * @param create The create to set.
     */
    public void setCreate(boolean create)
    {
        this.create = create;
    }
}
