/**
 * 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.jms;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.ow2.jonas.antmodular.jonasbase.bootstrap.AbstractJOnASBaseAntTask;
import org.ow2.jonas.antmodular.jonasbase.bootstrap.JReplace;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;


/**
 * Allow to configure the JMS service.
 * @author Florent Benoit
 */
public class Jms extends AbstractJOnASBaseAntTask {

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

    /**
     * Default host name.
     */
    private static final String DEFAULT_HOST = "localhost";

    /**
     * Default port number.
     */
    private static final String DEFAULT_PORT = "16010";

    /**
     * Name of Joram configuration file.
     */
    public static final String JORAM_CONF_FILE = "a3servers.xml";

    /**
     * Name of Joram Admin configuration file.
     */
    public static final String JORAM_ADMIN_CONF_FILE = "joramAdmin.xml";

    /**
     * JORAM Admin deployable file
     */
    public static final String JORAM_ADMIN_DEPLOYABLE_FILE = "joramAdminConfig.xml";

    /**
     * EOL
     */
    public static final String EOL = "\n";

    /**
     * Package of mandatory deployables
     */
    public static final String MANDATORY_DEPLOYABLE_PACKAGE = "templates/jms/joram/deploy/mandatory";

    /**
     * List of topics
     */
    private List<String> topics;

    /**
     * List of queues
     */
    private List<String> queues;

    /**
     * Default constructor.
     */
    public Jms() {
        super();
        this.topics = new ArrayList<String>();
        this.queues = new ArrayList<String>();
    }

    /**
     * Set the host name for Joram.
     * @param host host name for Joram
     */
    public void setHost(final String host) {

        // For JMS
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JORAM_CONF_FILE);
        propertyReplace.setToken(DEFAULT_HOST);
        propertyReplace.setValue(host);
        propertyReplace.setLogInfo(INFO + "Setting Joram host name to : " + host + " in "
                + JORAM_CONF_FILE + " file.");
        addTask(propertyReplace);

        // For correct binding of JCF, JQCF and JTCF in JNDI
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JORAM_ADMIN_CONF_FILE);
        propertyReplace.setToken(DEFAULT_HOST);
        propertyReplace.setValue(host);
        propertyReplace.setLogInfo(INFO + "Setting Joram host name to : " + host + " in "
                + JORAM_ADMIN_CONF_FILE + " file.");
        addTask(propertyReplace);

        // for RAR file
        propertyReplace = new JReplace();
        propertyReplace.setDeployableFile(JORAM_ADMIN_DEPLOYABLE_FILE);
        propertyReplace.setToken(DEFAULT_HOST);
        propertyReplace.setValue(host);
        propertyReplace.setLogInfo(INFO + "Setting Joram host name to : " + host + " in "
                + JORAM_ADMIN_DEPLOYABLE_FILE + " file.");
        addTask(propertyReplace);

        // Patch the RAR file
        JmsRa jmsRa = new JmsRa();
        jmsRa.setServerHost(host);
        addTask(jmsRa);

    }

    /**
     * Set the port number for Joram.
     * @param portNumber the port for Joram
     */
    public void setPort(final String portNumber) {

        // For JMS
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JORAM_CONF_FILE);
        propertyReplace.setToken(DEFAULT_PORT);
        propertyReplace.setValue(portNumber);
        propertyReplace.setLogInfo(INFO + "Setting Joram port number to : " + portNumber + " in "
                + JORAM_CONF_FILE + " file.");
        addTask(propertyReplace);

        // For correct binding of JCF, JQCF and JTCF in JNDI
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JORAM_ADMIN_CONF_FILE);
        propertyReplace.setToken(DEFAULT_PORT);
        propertyReplace.setValue(portNumber);
        propertyReplace.setLogInfo(INFO + "Setting Joram port number to : " + portNumber + " in "
                + JORAM_ADMIN_CONF_FILE + " file.");
        addTask(propertyReplace);

        // for RAR file
        propertyReplace = new JReplace();
        propertyReplace.setDeployableFile(JORAM_ADMIN_DEPLOYABLE_FILE);
        propertyReplace.setToken(DEFAULT_PORT);
        propertyReplace.setValue(portNumber);
        propertyReplace.setLogInfo(INFO + "Setting Joram port number to : " + portNumber + " in "
                + JORAM_ADMIN_DEPLOYABLE_FILE + " file.");
        addTask(propertyReplace);

        // Patch the RAR file
        JmsRa jmsRa = new JmsRa();
        jmsRa.setServerPort(portNumber);
        addTask(jmsRa);

    }

    /**
     * Set the initial topics when JOnAS start.
     * @param initialTopics comma separated list of topics
     */
    public void setInitialTopics(final String initialTopics) {
        StringTokenizer st = new StringTokenizer(initialTopics, ",");
        while (st.hasMoreTokens()) {
            this.topics.add(st.nextToken());
        }
    }

    /**
     * Set the initial queues when JOnAS start.
     * @param initialQueues comma separated list of topics
     */
    public void setInitialQueues(final String initialQueues) {
        StringTokenizer st = new StringTokenizer(initialQueues, ",");
        while (st.hasMoreTokens()) {
            this.queues.add(st.nextToken());
        }
    }

    /**
     * Execute all task
     */
    public void execute() {
        //copy mandatory template deployables
        copyTemplateDeployables(MANDATORY_DEPLOYABLE_PACKAGE);
        super.execute();
        super.executeAllTask();
        
        File joramConfig = new File(new File(getJOnASBase(), "deploy"), "joramAdminUserConfig.xml");
        FileOutputStream outputStream = null;

        try {
            try {
                outputStream = new FileOutputStream(joramConfig);
            } catch (FileNotFoundException e) {
                log("Cannot create file " + joramConfig.getAbsolutePath() + ": " + e, Project.MSG_ERR);
            }

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            stringBuilder.append(EOL + "<configadmin xmlns=\"http://jonas.ow2.org/ns/configadmin/1.0\">");

            List<String> names = new ArrayList<String>();
            names.addAll(this.topics);
            names.addAll(this.queues);
            for (String name: names) {                
                stringBuilder.append(EOL + "  <factory-configuration pid=\"org.objectweb.joram.client.osgi.DestinationMSF\">");
                stringBuilder.append(EOL + "    <property name=\"adminWrapper\">ra</property>");
                stringBuilder.append(EOL + "    <property name=\"serverId\">0</property>");
                stringBuilder.append(EOL + "    <property name=\"name\">" + name + "</property>");
                
                String classname;
                if (this.topics.contains(name)) {
                    classname = "org.objectweb.joram.mom.dest.Topic";
                } else {
                    classname = "org.objectweb.joram.mom.dest.Queue";
                }
                
                stringBuilder.append(EOL + "    <property name=\"className\">" + classname + "</property>");
                stringBuilder.append(EOL + "    <property name=\"freeReading\">true</property>");
                stringBuilder.append(EOL + "    <property name=\"freeWriting\">true</property>");
                stringBuilder.append(EOL + "    <property name=\"jndiName\">" + name + "</property>");
                stringBuilder.append(EOL + "  </factory-configuration>");
            }
            
            stringBuilder.append(EOL + "</configadmin>");

            try {
                outputStream.write(stringBuilder.toString().getBytes());
            } catch (IOException e) {
                log("Cannot write " + stringBuilder.toString() + " into the output file " + joramConfig.getAbsolutePath()
                        + " :" + e, Project.MSG_ERR);
            }

        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                log("Cannot close the FileOutputStream resource " + e, Project.MSG_ERR);
            }
        }
    }
}
