/**
 * 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.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * JOnAS glue for Eclipse Compiler.
 * @author Guillaume Sauthier
 */
public class JOnASCompilerRequestor implements ICompilerRequestor {

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

    /**
     * Directory where generated files will be placed.
     */
    private File outputDirectory;

    /**
     * Compilation process errors.
     */
    private List<CompilerError> errors;

    /**
     * Creates a new {@link ICompilerRequestor}.
     * @param outputDirectory Directory where generated files will be placed.
     * @param errors Compilation process errors.
     */
    public JOnASCompilerRequestor(final File outputDirectory,
                                  final List<CompilerError> errors) {
        super();
        this.outputDirectory = outputDirectory;
        this.errors = errors;
    }

    /**
     * Analyze the compilation process results and store the generated class files on the disk.
     * This is called for each {@link ICompilationUnit}.
     * @see org.eclipse.jdt.internal.compiler.ICompilerRequestor#acceptResult(org.eclipse.jdt.internal.compiler.CompilationResult)
     */
    public void acceptResult(final CompilationResult result) {

        if (result.hasErrors()) {
            // Handle compilation Errors
            IProblem[] problems = result.getErrors();

            for (int i = 0; i < problems.length; i++) {
                IProblem problem = problems[i];

                String name = new String(problems[i].getOriginatingFileName());
                errors.add(new CompilerError(name, problem));
            }
        } else {
            // Get the generated files
            ClassFile[] classFiles = result.getClassFiles();

            // For each class file ...
            for (int i = 0; i < classFiles.length; i++) {
                ClassFile classFile = classFiles[i];

                // Re-creates a fully qualified Java class name
                String className = new String(CharOperation.concatWith(classFile.getCompoundName(), '.'));

                // Get content
                byte[] bytes = classFile.getBytes();

                log.debug("Storing class: {0}", className);

                // Creates the directory structure
                File outFile = new File(outputDirectory,
                                        className.replace('.', File.separatorChar) + ".class");
                if (!outFile.getParentFile().exists()) {
                    outFile.getParentFile().mkdirs();
                }

                // Store the class file content on the disk
                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(outFile);
                    fout.write(bytes);
                    fout.flush();
                } catch (FileNotFoundException e) {
                    errors.add(new CompilerError(className, e));
                } catch (IOException e) {
                    errors.add(new CompilerError(className, e));
                } finally {
                    if (fout != null) {
                        try {
                            fout.close();
                        } catch (IOException e) {
                            // Ignore
                        }
                    }
                }
            }
        }
    }
}
