/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004-2011 Bull S.A.S.
 * Contact: jonas-team@ow2.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.ow2.jonas.antmodular.jonasbase.resource;

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

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.Path;
import org.ow2.jonas.antmodular.jonasbase.bootstrap.AbstractJOnASBaseAntTask;


import org.ow2.jonas.antmodular.jonasbase.bootstrap.JTask;


/**
 * Allow to create JDBC resource adaptors.
 * @author Florent Benoit
 */
public class JdbcRa extends AbstractJOnASBaseAntTask {

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

    /**
     * Name of the rar for JDBC_DM.
     */
    private static final String JONAS_JDBCDM = "jonas-jca-jdbc-dm";

    /**
     * RAConfig classname.
     */
    private static final String RACONFIG_CLASS = "org.ow2.jonas.generators.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 P6Spy configuration file.
     */
    public static final String P6SPY_CONF_FILE = "spy.properties";

    /**
     * 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.
     */
    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
     */
    /**
     * JNDI Name of this JDBC Resource Adaptor.
     */
    private String jndiName = null;

    /**
     * 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(final 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(final 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(final 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(final 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(final 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(final 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(final 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(final String maxWaitTime) {
        this.maxWaitTime = maxWaitTime;
    }

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

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

    /**
     * Set the open time max of this JDBC Resource Adaptor Connection Pool.
     * @param maxWaiters of connection
     */
    public void setMaxOpenTime(final 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(final 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(final 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.
     */
    @Override
    public void execute() {
        super.execute();
        JTask jtask = new JTask();
        jtask.setDestDir(destDir);

        // 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();
        jtask.writePropsToFile(INFO, props, tmpFile);

        // Build resource adapter for this configuration

        // args
        String jBaseDeployDir = this.destDir.getPath() + File.separator + "deploy";

        String jdbcDM = this.jonasRoot.getPath() + File.separator + jtask.getMaven2Repository() + File.separator + "org"
                + File.separator + "ow2" + File.separator + "jonas" + File.separator + JONAS_JDBCDM + File.separator
                + getJOnASVersion() + File.separator + JONAS_JDBCDM + "-" + getJOnASVersion() + ".rar";
        String destRarFile = jBaseDeployDir + File.separator + name + ".rar";

     log("jonasRoot.getAbsolutePath()"+jonasRoot.getAbsolutePath());
        getProject().setProperty("jonas.root",jonasRoot.getAbsolutePath());
        jtask.setJonasRoot(this.jonasRoot);
        log("jtask.getJonasRoot():"+jtask.getJonasRoot());
        Java raConfigTask = jtask.getBootstraptask("", false, getProject());

        // Add the ra-config Jar in the Java classpath path
        String clientJar = this.jonasRoot.getPath() + File.separator + "lib" + File.separator + "client.jar";
        String raConfigJar = this.jonasRoot.getPath() + File.separator + "lib" + File.separator + "jonas-generators-raconfig.jar";
        Path classpath = new Path(raConfigTask.getProject(), clientJar);
        classpath.append(new Path(raConfigTask.getProject(), raConfigJar));
        raConfigTask.setClasspath(classpath);

        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 = this.jonasRoot.getPath() + File.separator + "conf";
            jtask.changeValueForKey(INFO, jBaseConf, P6SPY_CONF_FILE,
                    REALDRIVER_PROPERTY, realDriverName, "=", false);
            addTask(jtask);
        }

        super.executeAllTask();
    }

    /**
     * Copy rar to autoload or only in rars/ ?
     * @param autoload true of false
     * @deprecated
     */
    @Deprecated
    public void setAutoload(final boolean 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(final boolean p6spy) {
        this.p6spy = p6spy;
    }

    private String getJOnASVersion() {
        Properties versions = new Properties();
        try {
            versions.load(new FileInputStream(new File(this.jonasRoot, "versions.properties")));
        } catch (Exception e) {
            throw new BuildException(INFO + "Cannot read versions.properties file: ", e);
        }
        return versions.getProperty("org.ow2.jonas");
    }
}
