/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library 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 any later version.
 *
 * This library 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.ant.jonasbase;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Java;

import org.objectweb.jonas.ant.JOnASBaseTask;

/**
 * Allow to create JDBC resource adaptors
 * @author Florent Benoit
 */
public class JdbcRa extends JTask implements BaseTaskItf {

    /**
     * Info for the logger
     */
    private static final String INFO = "[JdbcRa] ";

    /**
     * Name of the rar for JDBC_DM
     */
    private static final String JONAS_JDBCDM = "JOnAS_jdbcDM";

    /**
     * RAConfig classname
     */
    private static final String RACONFIG_CLASS = "org.objectweb.jonas_rar.raconfig.RAConfig";

    /**
     * P6Spy driver class name
     */
    private static final String P6SPY_DRIVER = "com.p6spy.engine.spy.P6SpyDriver";

    /**
     * Name of the property of the real driver when using P6Spy tool
     */
    private static final String REALDRIVER_PROPERTY = "realdriver";

    /**
     * Name of this JDBC Resource Adaptor
     */
    private String name = null;

    /**
     * Mapper Name of this JDBC Resource Adaptor
     */
    private String mapperName = null;

    /**
     * username of this JDBC Resource Adaptor
     */
    private String user = null;

    /**
     * Password of this JDBC Resource Adaptor
     */
    private String password = null;

    /**
     * URL of this JDBC Resource Adaptor
     */
    private String url = null;

    /**
     * Driver Name of this JDBC Resource Adaptor (may be set to the P6Spy driver name)
     */
    private String driverName = null;

    /**
     * Driver Name of this JDBC Resource Adaptor
     */
    private String realDriverName = null;

    /**
     * Max Pool Size jdbc
     */
    private String maxPoolSize = "100";

    /**
     * Max Prepared Statements Size
     */
    private String maxPreparedStatementsSize = "10";

    /**
     * Max Wait Time jdbc
     */
    private String maxWaitTime = "10";

    /**
     * Max Waiters jdbc
     */
    private String maxWaiters = "0";

    /**
     * connexion max age jdbc
     */
    private String connMaxAge = "0";

    /**
     * Max open time jdbc
     */
    private String maxOpenTime = "0";

    /**
     * JNDI Name of this JDBC Resource Adaptor
     */
    private String jndiName = null;

    /**
     * Copy to autoload dir or not
     */
    private boolean autoload = true;

    /**
     * Using of the P6Spy tool or not
     */
    private boolean p6spy = false;

    /**
     * Set the name of this JDBC Resource Adaptor
     * @param name the name of this JDBC Resource Adaptor
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Set the mapper name of this JDBC Resource Adaptor
     * @param mapperName the mappername of this JDBC Resource Adaptor
     */
    public void setMapperName(String mapperName) {
        this.mapperName = mapperName;
    }

    /**
     * Set the user of this JDBC Resource Adaptor
     * @param user the user of this JDBC Resource Adaptor
     */
    public void setUser(String user) {
        this.user = user;
    }

    /**
     * Set the password of this JDBC Resource Adaptor
     * @param password the name of this JDBC Resource Adaptor
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Set the url of this JDBC Resource Adaptor
     * @param url the name of this JDBC Resource Adaptor
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * Set the max pool size of this JDBC Resource Adaptor Connection Pool
     * @param maxPoolSize max pool size of connection
     */
    public void setMaxPoolSize(String maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    /**
     * Set the max prepared Statements size of this JDBC Resource Adaptor Connection Pool
     * @param maxPreparedStatementsSize of connection
     */
    public void setMaxPreparedStatementsSize(String maxPreparedStatementSize) {
        this.maxPreparedStatementsSize = maxPreparedStatementSize;
    }

    /**
     * Set the max wait time of this JDBC Resource Adaptor Connection Pool
     * @param maxWaitTime of the connection
     */
    public void setMaxWaitTime(String maxWaitTime) {
        this.maxWaitTime = maxWaitTime;
    }

    /**
     * Set the max waiters of this JDBC Resource Adaptor Connection Pool
     * @param maxWaiters of connection
     */
    public void setMaxWaiters(String maxWaiters) {
        this.maxWaiters = maxWaiters;
    }

    /**
     * Set the max aiters of this JDBC Resource Adaptor Connection Pool
     * @param maxWaiters of connection
     */
    public void setConnMaxAge(String connMaxAge) {
        this.connMaxAge = connMaxAge;
    }

    /**
     * Set the max aiters of this JDBC Resource Adaptor Connection Pool
     * @param maxWaiters of connection
     */
    public void setMaxOpenTime(String maxOpenTime) {
        this.maxOpenTime = maxOpenTime;
    }

    /**
     * Set the name of the driver of this JDBC Resource Adaptor
     * @param driverName the name of the driver of this JDBC Resource Adaptor
     */
    public void setDriverName(String driverName) {
        this.driverName = driverName;
        this.realDriverName = driverName;
    }

    /**
     * Set the jndiName of this JDBC Resource Adaptor
     * @param jndiName the jndiName of this JDBC Resource Adaptor
     */
    public void setJndiName(String jndiName) {
        this.jndiName = jndiName;
    }

    /**
     * Check the properties
     */
    private void checkProperties() {
        if (name == null) {
            throw new BuildException(INFO + "Property 'name' is missing.");
        } else if (mapperName == null) {
            throw new BuildException(INFO + "Property 'mapperName' is missing.");
        } else if (user == null) {
            throw new BuildException(INFO + "Property 'user' is missing.");
        } else if (password == null) {
            throw new BuildException(INFO + "Property 'password' is missing.");
        } else if (url == null) {
            throw new BuildException(INFO + "Property 'url' is missing.");
        } else if (driverName == null) {
            throw new BuildException(INFO + "Property 'driverName' is missing.");
        } else if (jndiName == null) {
            throw new BuildException(INFO + "Property 'jndiName' is missing.");
        }
    }

    /**
     * Gets a Properties object for JDBC
     * @return configured properties
     */
    private Properties getProperties() {
        // Check properties
        checkProperties();

        Properties props = new Properties();
        props.put("datasource.name", jndiName);
        props.put("datasource.url", url);
        if (p6spy) {
            driverName = P6SPY_DRIVER;
        }
        props.put("datasource.classname", driverName);
        props.put("datasource.username", user);
        props.put("datasource.password", password);
        props.put("datasource.mapper", mapperName);
        props.put("jdbc.maxconpool", maxPoolSize);
        props.put("jdbc.pstmtmax", maxPreparedStatementsSize);
        props.put("jdbc.maxwaittime", maxWaitTime);
        props.put("jdbc.maxwaiters", maxWaiters);
        props.put("jdbc.connmaxage", connMaxAge);
        props.put("jdbc.maxopentime", maxOpenTime);
        return props;
    }

    /**
     * Execute this task
     */
    public void execute() {

        // Build new temp file for making a resource adaptor
        File tmpFile = new File(System.getProperty("java.io.tmpdir"), String.valueOf(new Date().getTime()));

        // Write properties to a file
        Properties props = getProperties();
        writePropsToFile(INFO, props, tmpFile);

        // Build resource adapter for this configuration

        // args
        String jRootRarsDir = getJonasRoot().getPath() + File.separator + "rars" + File.separator + "autoload";
        String jBaseRarsDir = getDestDir().getPath() + File.separator + "rars";
        if (isAutoload()) {
            jBaseRarsDir += File.separator + "autoload";
        }
        String jdbcDM = jRootRarsDir + File.separator + JONAS_JDBCDM;
        String destRarFile = jBaseRarsDir + File.separator + name + ".rar";

        Java raConfigTask = getBootstraptask("");
        raConfigTask.clearArgs();
        raConfigTask.createArg().setValue(RACONFIG_CLASS);
        raConfigTask.createArg().setValue("-dm");
        raConfigTask.createArg().setValue("-p");
        raConfigTask.createArg().setValue(tmpFile.getPath());
        raConfigTask.createArg().setValue(jdbcDM);
        raConfigTask.createArg().setValue(destRarFile);

        log(INFO + "Generating a rar file with name '" + name + "', mapperName '" + mapperName + "', user '" + user
                + "', password '" + password + "', URL '" + url + "', driverName '" + driverName + "' and jndiName '"
                + jndiName + "'...");

        try {
            raConfigTask.execute();
        } catch (Exception rae) {
            rae.printStackTrace();
            throw new BuildException(INFO + "Cannot make a resource adaptor on RAConfig: ", rae);
        } finally {
            tmpFile.delete();
        }
        log(INFO + "Rar generated : '" + destRarFile + "'.");

        // P6Spy tool Configuration
        if (p6spy) {
            // Set the realdriver property of the JONAS_BASE/conf/spy.properties P6Spy configuration file
            String jBaseConf = getJonasRoot().getPath() + File.separator + "conf";
            changeValueForKey(INFO, jBaseConf, JOnASBaseTask.P6SPY_CONF_FILE,
                    REALDRIVER_PROPERTY, realDriverName, "=", false);
        }
    }

    /**
     * Copy rar to autoload or only in rars/ ?
     * @return the autoload.
     */
    public boolean isAutoload() {
        return autoload;
    }

    /**
     * opy rar to autoload or only in rars/ ?
     * @param autoload true of false
     */
    public void setAutoload(boolean autoload) {
        this.autoload = autoload;
    }

    /**
     * Configure the using of the P6Spy tool or not ?
     * @return the p6spy
     */
    public boolean isP6spy() {
        return p6spy;
    }

    /**
     * Configure the using of the P6Spy tool or not ?
     * @param p6spy true or false
     */
    public void setP6spy(boolean p6spy) {
        this.p6spy = p6spy;
    }
}