/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004-2005 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_lib.genclientstub;

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

import org.objectweb.jonas_lib.genbase.archive.Archive;
import org.objectweb.jonas_lib.genbase.generator.Config;
import org.objectweb.jonas_lib.genbase.generator.GeneratorFactories;
import org.objectweb.jonas_lib.genbase.modifier.ArchiveModifier;
import org.objectweb.jonas_lib.genbase.utils.TempRepository;
import org.objectweb.jonas_lib.genclientstub.generator.GeneratorFactory;
import org.objectweb.jonas_lib.genclientstub.modifier.ModifierFactory;

import org.objectweb.jonas_ws.wsgen.NoJ2EEWebservicesException;

import org.objectweb.jonas.common.Log;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * 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(Log.JONAS_CLIENTSTUBGEN_PREFIX);

    /**
     * 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(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(String[] args) throws Exception {
        GeneratorFactory gf = GeneratorFactory.getInstance();

        // store configuration properties
        Config config = parseInput(args);

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

        // 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());

            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 (modifiedArchive != null) {
                modifiedArchive.close();
            }
            modifiedArchive = null;
            am = null;

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

    }

    /**
     * Parse Command Line input and returns a Config object
     * @param args Command Lines params
     * @return a Config object
     */
    private static Config parseInput(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.objectweb.jonas_lib.genclientstub.ClientStubgen -help \n");
        msg.append("   to print this help message \n");
        msg.append(" or java org.objectweb.jonas_lib.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;
    }
}