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

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.objectweb.util.monolog.api.BasicLevel;
import org.ow2.jonas.eclipse.compiler.CompilationContext;
import org.ow2.jonas.eclipse.compiler.CompilerError;
import org.ow2.jonas.eclipse.compiler.JOnASCompiler;
import org.ow2.jonas.generators.genbase.GenBaseException;
import org.ow2.jonas.generators.genbase.generator.AbsGenerator;
import org.ow2.jonas.generators.genbase.generator.Config;
import org.ow2.jonas.generators.wsgen.WsGenException;
import org.ow2.jonas.lib.bootstrap.loader.JClassLoader;
import org.ow2.jonas.lib.util.I18n;

/**
 * Generators provide a structure to be extended for specific generation
 * mecanisms. Axis will provide an AxisWsClientGenerator that will be in charge
 * of client side generation (WSDL2Java tool) and an AxisWsEndpointGenerator
 * that will bother with server side artifact generation.
 *
 * @author Guillaume Sauthier
 */
public abstract class Generator extends AbsGenerator {

    /**
     * i18n.
     */
    private static I18n i18n = I18n.getInstance(Generator.class);

    /**
     * Creates a new Generator with the given Config.
     *
     * @param config internal configuration object.
     *
     * @throws GenBaseException When sources and target temporary directory cannot
     *         be created
     */
    public Generator(final Config config) throws GenBaseException {
        super(config);
    }

    /**
     * Generate files.
     *
     * @throws WsGenException When generation fails.
     */
    @Override
    public abstract void generate() throws WsGenException;

    /**
     * Compile generated java files into classes directory.
     *
     * @throws WsGenException When compilation fails
     */
    @Override
    public void compile() throws WsGenException {
        // get all java files contained in the sources dir
        List<String> sources = new ArrayList<String>();
        sources = getJavaSources(getSources(), getSources());

        // Init the compilation context
        CompilationContext context = new CompilationContext();

        JClassLoader classLoader = new  JClassLoader("WSGen", new URL[]{}, Thread.currentThread().getContextClassLoader());
        addClasspath(classLoader, getConfig().getClasspath());
        context.setContextualClassLoader(classLoader);

        context.setOutputDirectory(getClasses());
        context.setSourceDirectory(getSources());
        context.setSources(sources);

        // Compile
        JOnASCompiler compiler = new JOnASCompiler(context);

        List<CompilerError> errors = compiler.compile();
        if (errors.isEmpty()) {
            getLogger().log(BasicLevel.INFO, "Sources classes successfully compiled with Eclipse compiler.");
        } else {
            for (CompilerError error : errors) {
                getLogger().log(BasicLevel.ERROR, error.toString());
            }
            throw new WsGenException("Failed when compiling classes");
        }

        classLoader = null;
        context = null;
        compiler = null;

        // Perform garbage collector
        System.gc();
    }

    /**
     * Add To the given ClassLoader the given classpath.
     * @param cl ClassLoader to be updated
     * @param classpath the classpath to add inside the ClassLoader
     * @throws WsGenException When classpath contains invalid URL
     */
    private static void addClasspath(final JClassLoader cl,
                                     final String classpath) throws WsGenException {
        String[] elems = classpath.split(File.pathSeparator);
        for (int i = 0; i < elems.length; i++) {
            try {
                cl.addURL(new File(elems[i]).toURL());
            } catch (MalformedURLException e) {
                throw new WsGenException("Cannot create URL from '" + elems[i] + "'", e);
            }
        }
    }


    /**
     * @return the i18n.
     */
    protected static I18n getI18n() {
        return i18n;
    }
}
