/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.eclipse.compiler;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Central piece of JOnAS glue for eclipse compiler integration.
 * @author Guillaume Sauthier
 */
public class JOnASNameEnvironment implements INameEnvironment {

    /**
     * Logger.
     */
    private static final Log log = LogFactory.getLog(JOnASNameEnvironment.class);

    /**
     * Compilation Context.
     */
    private CompilationContext context;

    /**
     * List of generated errors.
     */
    private List<CompilerError> errors;

    /**
     * Creates a new {@link JOnASNameEnvironment} glue.
     * @param context CompilationContext
     * @param errors list of compilation errors
     */
    public JOnASNameEnvironment(final CompilationContext context,
                                final List<CompilerError> errors) {
        this.context = context;
        this.errors = errors;
    }

    /**
     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#cleanup()
     */
    public void cleanup() {
        // nothing to clean
    }

    /**
     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#findType(char[][])
     */
    public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {

        // Creates a fully qualified Java class name
        String result = new String(CharOperation.concatWith(compoundTypeName, '.'));

        log.debug("------------- Entering: findType(type:{0})", result);

        return findType(result);
    }

    /**
     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#findType(char[],
     *      char[][])
     */
    public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) {

        // Creates a fully qualified Java class name
        String result = new String(CharOperation.concatWith(packageName, '.'));

        log.debug("------------- Entering: findType(package:{0}, typeName:{1})", result, new String(typeName));

        // append the type name to the package
        result += ".";
        result += new String(typeName);

        return findType(result);
    }

    /**
     * @return an {@link ICompilationUnit} if the class name match a source
     * file that has to be compiled. Otherwise, load the dependency byte code
     * from the context class loader.
     * @param className classname to find
     */
    private NameEnvironmentAnswer findType(final String className) {
        try {
            log.debug("'"+ className + "' processing");

            // Try to locate a java source file from the class name
            String javaSource = className.replace(".", File.separator) + ".java";
            File f = new File(context.getSourceDirectory(), javaSource);

            if (f.exists()) {

                log.debug("Found matching java source file '{0}'", f);

                // If the file is found, then return an ICompilationUnit
                ICompilationUnit compilationUnit = new JOnASCompilationUnit(className,
                                                                            f.getAbsolutePath(),
                                                                            context,
                                                                            errors);

                return new NameEnvironmentAnswer(compilationUnit, null);
            }

            // In the other case (file not found), try to find the class file
            // byte code from the ClassLoader
            String resourceName = className.replace('.', '/') + ".class";
            InputStream is = context.getContextualClassLoader().getResourceAsStream(resourceName);

            if (is == null) {

                log.debug("Didn't find the class resource '{0}'", resourceName);
                // if class file is not found, simply returns
                return null;
            }

            // Constructs the class file reader from the IS
            ClassFileReader classFileReader = ClassFileReader.read(is, resourceName);

            return new NameEnvironmentAnswer(classFileReader, null);
        } catch (IOException e) {
            errors.add(new CompilerError(className, e));
            return null;
        } catch (ClassFormatException e) {
            errors.add(new CompilerError(className, e));
            return null;
        }
    }

    /**
     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#isPackage(char[][],
     *      char[])
     */
    public boolean isPackage(final char[][] parentPackageName, final char[] packageName) {
        String result = "";

        // Construct a String package name by concatenation
        if (parentPackageName != null) {
            result = new String(CharOperation.concatWith(parentPackageName, '.'));
        }

        log.debug("=============== Entering: isPackage(parent:{0}, name:{1})", result, new String(packageName));

        // Continue concatenation
        String str = new String(packageName);
        result += ".";
        result += str;

        return isPackage(result);
    }

    /**
     * @param potentialPackage the potential package name to be tested
     * @return true if the String parameter is a java package, false
     *         otherwise.
     */
    private boolean isPackage(final String potentialPackage) {

        log.debug("isPackage({0})", potentialPackage);

        // Try to see if a .java class exists
        String javaSource = potentialPackage.replace(".", File.separator) + ".java";
        File f = new File(context.getSourceDirectory(), javaSource);
        if (f.exists()) {
            log.debug("Found a java file {0}", f);
            // if so, directly return false
            return false;
        }

        // Try to see if there is an associated resource in the classloader
        String resourceName = potentialPackage.replace('.', '/') + ".class";
        InputStream is = context.getContextualClassLoader().getResourceAsStream(resourceName);

        // if so return false, any other case return true.
        return is == null;
    }
}
