/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004-2008 Bull S.A.
 * 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.generators.genclientstub;

import java.io.File;
import java.util.StringTokenizer;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.generators.genbase.NoJ2EEWebservicesException;
import org.ow2.jonas.generators.genbase.archive.Archive;
import org.ow2.jonas.generators.genbase.generator.Config;
import org.ow2.jonas.generators.genbase.generator.GeneratorFactories;
import org.ow2.jonas.generators.genbase.modifier.ArchiveModifier;
import org.ow2.jonas.generators.genbase.utils.TempRepository;
import org.ow2.jonas.generators.genclientstub.generator.GeneratorFactory;
import org.ow2.jonas.generators.genclientstub.modifier.ModifierFactory;
import org.ow2.jonas.lib.util.Log;
import org.ow2.util.ee.deploy.api.deployable.IDeployable;

/**
 * Main class of the client stub generator Class. Some code come from WsGen
 * classes (Guillaume Sauthier)
 * @author Florent Benoit
 */
public class ClientStubGen {

    /**
     * logger.
     */
    private static Logger logger = Log.getLogger("org.ow2.jonas.generators.genclientstub");

    /**
     * Set to false if input file cannot be processed (DTDs).
     */
    private boolean inputModified = true;

    /**
     * Private Constructor for Utility class.
     */
    public ClientStubGen() {
    }

    /**
     * Main method.
     * @param args Commend line args
     * @throws Exception When the execute method fails
     */
    public static void main(final String[] args) throws Exception {
        ClientStubGen stubGen = new ClientStubGen();
        stubGen.execute(args);
    }

    /**
     * Method used by main method and by external class to retrieve the name of
     * the modified or created file by ClientStubGen.
     * @param args command line arguments
     * @return the name of the modified or built
     * @throws Exception When a failure occurs
     */
    public String execute(final String[] args) throws Exception {
        // store configuration properties
        Config config = parseInput(args);

        if (config.isHelp() || config.isError() || config.getInputname() == null) {
            // display usage message
            usage();
            return null;
        }

        return execute(config, null);
    }

    /**
     * Method used by main method and by external class to retrieve the name of
     * the modified or created file by ClientStubGen.
     * @param config the given config
     * @param deployable the deployable to analyze
     * @return the name of the modified or built
     * @throws Exception When a failure occurs
     */
    public String execute(final Config config, final IDeployable<?> deployable) throws Exception {
        GeneratorFactory gf = GeneratorFactory.getInstance();

        // For this client generator, the use of DTDs is allowed
        config.setDTDsAllowed(true);

        // setup configuration
        gf.setConfiguration(config);
        GeneratorFactories.setCurrentFactory(gf);
        Archive modifiedArchive = null;
        ArchiveModifier am = null;
        // get the ArchiveModifier
        try {
            //TODO : get DTD only exception
            am = ModifierFactory.getModifier(config.getInputname(), true, deployable);

            logger.log(BasicLevel.INFO, "Client stub generation for '" + config.getInputname() + "'");

            // modify the given archive
            modifiedArchive = am.modify();

            // Get path
            String path = modifiedArchive.getRootFile().getCanonicalPath();

            return path;
        } catch (NoJ2EEWebservicesException e) {
            logger.log(BasicLevel.WARN, config.getInputname() + "Error while generating stubs : '" + e.getMessage()
                    + "'");
            inputModified = false;
            return config.getInputname();
        } finally {
            // close archive
            if (am != null && am.getArchive() != null) {
                am.getArchive().close();
            }

            modifiedArchive = null;
            am = null;

            // delete all the temporary files created
            TempRepository.getInstance().deleteAll();

            System.gc();
        }

    }

    /**
     * Parse Command Line input and returns a Config object.
     * @param args Command Lines params
     * @return a Config object
     */
    private static Config parseInput(final String[] args) {
        Config config = new Config();

        // Get args
        for (int argn = 0; argn < args.length; argn++) {
            String arg = args[argn];

            if (arg.equals("-help") || arg.equals("-?")) {
                config.setHelp(true);

                continue;
            }

            if (arg.equals("-verbose")) {
                config.setVerbose(true);

                continue;
            }

            if (arg.equals("-debug")) {
                config.setDebug(true);
                config.setVerbose(true);

                continue;
            }

            if (arg.equals("-keepgenerated")) {
                config.setKeepGenerated(true);

                continue;
            }

            if (arg.equals("-noconfig")) {
                config.setNoConfig(true);

                continue;
            }

            if (arg.equals("-novalidation")) {
                config.setParseWithValidation(false);

                continue;
            }

            if (arg.equals("-javac")) {
                config.setNameJavac(args[++argn]);

                continue;
            }

            if (arg.equals("-javacopts")) {
                argn++;

                if (argn < args.length) {
                    StringTokenizer st = new StringTokenizer(args[argn]);

                    while (st.hasMoreTokens()) {
                        config.getJavacOpts().add(st.nextToken());
                    }
                } else {
                    config.setError(true);
                }

                continue;
            }

            if (arg.equals("-d")) {
                argn++;

                if (argn < args.length) {
                    config.setOut(new File(args[argn]));
                } else {
                    config.setError(true);
                }

                continue;
            }

            if (args[argn] != null) {
                config.setInputname(args[argn]);
            } else {
                config.setError(true);
            }
        }

        return config;

    }

    /**
     * Display the usage.
     */
    public static void usage() {
        StringBuffer msg = new StringBuffer();
        msg.append("Usage: java org.ow2.jonas.generators.genclientstub.ClientStubgen -help \n");
        msg.append("   to print this help message \n");
        msg.append(" or java org.ow2.jonas.generators.genclientstub.ClientStubgen <Options> <Input_File> \n");
        msg.append("Options include: \n");
        msg.append("    -d <output_dir>  specify where to place the generated files \n");
        msg.append("    -novalidation parse the XML deployment descriptors without \n");
        msg.append("      validation \n");
        msg.append("    -javac  <opt> specify the java compiler to use \n");
        msg.append("    -javacopts <opt> specify the options to pass to the java compiler \n");
        msg.append("    -keepgenerated   do not delete intermediate generated files \n");
        msg.append("    -noconfig  do not generate configuration files (require \n");
        msg.append("      user provided files) \n");
        msg.append("    -verbose \n");
        msg.append("    -debug \n");
        msg.append(" \n");
        msg.append("    Input_File    the ejb-jar, war or ear filename\n");
        System.out.println(msg.toString());
    }

    /**
     * @return the inputModified flag
     */
    public boolean isInputModified() {
        return inputModified;
    }
}
