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

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.ow2.jonas.lib.bootstrap.JProp;
import org.ow2.jonas.lib.bootstrap.LoaderManager;


/**
 * WSGen wrapper Used to launch WsGen in DeployFile of JSR 88
 * @author Florent Benoit
 */
public class WsGenWrapper {

    /**
     * WsGen fully qualified classname
     */
    private static final String WSGEN_CLASSNAME = "org.ow2.jonas.generators.wsgen.WsGen";

    /**
     * Number of arguments of execute method
     */
    private static final int ARGS_NUMBER = 3;

    /**
     * Method execute of WsGen
     */
    private static Method executeMethod = null;

    /**
     * WsGen has changed the archive or not ?
     */
    private static Method isInputModifiedMethod = null;

    /**
     * WsGen class
     */
    private Object wsgen = null;

    /**
     * Empty constructor.
     */
    public WsGenWrapper() {
    };

    /**
     * Wrapper around WsGen.execute(String[]) method
     * @param fileName name of the file
     * @return name of the modified/built file
     * @throws Exception If WsGen fails or if Reflection errors occurs
     */
    public String callWsGenExecute(final String fileName) throws Exception {
        return callWsGenExecute(fileName, Boolean.FALSE);
    }
    /**
     * Wrapper around WsGen.execute(String[]) method
     * @param fileName name of the file
     * @param unpacked true if the result must be packed in a directory (default = false)
     * @return name of the modified/built file
     * @throws Exception If WsGen fails or if Reflection errors occurs
     */
    public String callWsGenExecute(final String fileName, final Boolean unpacked) throws Exception {
        LoaderManager lm = LoaderManager.getInstance();
        ClassLoader old = null;

        try {
            ClassLoader ext = lm.getExternalLoader();
            old = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(ext);

            if (executeMethod == null) {
                Class clazz = ext.loadClass(WSGEN_CLASSNAME);
                executeMethod = clazz.getDeclaredMethod("execute", new Class[] {String[].class});
            }

            if (wsgen == null) {
                Class clazz = ext.loadClass(WSGEN_CLASSNAME);
                wsgen = clazz.newInstance();
            }

            String[] args = null;
            if (unpacked.booleanValue()) {
                args = new String[ARGS_NUMBER + 1];
            } else {
                args = new String[ARGS_NUMBER];
            }
            args[0] = "-d";
            args[1] = JProp.getWorkDir();
            if (unpacked.booleanValue()) {
                args[2] = "-unpacked";
                args[2 + 1] = fileName;
            } else {
                args[2] = fileName;
            }


            return (String) executeMethod.invoke(wsgen, new Object[] {args});
        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof Error) {
                throw (Error) e.getTargetException();
            } else {
                throw new Exception("Exception when executing WsGen.execute(String[])", e.getTargetException());
            }
        } catch (Exception e) {
            throw new Exception("Problems when invoking method WsGen.execute(String[])", e);
        } finally {
            if (old != null) {
                Thread.currentThread().setContextClassLoader(old);
            }
        }
    }

    /**
     * Wrapper around WsGen.isModified() method
     * @return true/false
     * @throws Exception If WsGen fails or if Reflection errors occurs
     */
    public boolean callWsGenIsInputModifed() throws Exception {
        LoaderManager lm = LoaderManager.getInstance();
        ClassLoader old = null;

        try {
            ClassLoader ext = lm.getExternalLoader();
            old = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(ext);

            if (isInputModifiedMethod == null) {
                Class clazz = ext.loadClass(WSGEN_CLASSNAME);
                isInputModifiedMethod = clazz.getDeclaredMethod("isInputModified", new Class[] {});
            }

            if (wsgen == null) {
                Class clazz = ext.loadClass(WSGEN_CLASSNAME);
                wsgen = clazz.newInstance();
            }

            return ((Boolean) isInputModifiedMethod.invoke(wsgen, (Object[]) null)).booleanValue();
        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof Error) {
                throw (Error) e.getTargetException();
            } else {
                throw new Exception("Exception when executing WsGen.isInputModified()", e.getTargetException());
            }
        } catch (Exception e) {
            throw new Exception("Problems when invoking method WsGen.isInputModified()", e);
        } finally {
            if (old != null) {
                Thread.currentThread().setContextClassLoader(old);
            }
        }
    }
}

