/*
 * Copyright (C) 2006-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.codehaus.gmaven.runtime.v1_7;

import groovy.lang.GroovyClassLoader;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.Phases;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.tools.javac.JavaAwareResolveVisitor;
import org.codehaus.groovy.tools.javac.JavaCompiler;
import org.codehaus.groovy.tools.javac.JavaStubGenerator;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * Java-stub-only compilation unit.
 *
 * @version $Id$
 * @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
 *
 * @since 1.1
 */
public class JavaStubCompilationUnit
    extends CompilationUnit
{
    private static final String DOT_GROOVY = ".groovy";
    
    private final JavaStubGenerator stubGenerator;

    private int stubCount;

    public JavaStubCompilationUnit(final CompilerConfiguration config, final GroovyClassLoader gcl, File destDir) {
        super(config,null,gcl);
        assert config != null;

        Map options = config.getJointCompilationOptions();
        if (destDir == null) {
            destDir = (File) options.get("stubDir");
        }
        boolean useJava5 = config.getTargetBytecode().equals(CompilerConfiguration.POST_JDK5);
        stubGenerator = new JavaStubGenerator(destDir, false, useJava5);

        // Copied from groovy/core, trying to see how to fix import problems
//        addPhaseOperation(new PrimaryClassNodeOperation()
//        {
//            public void call(final SourceUnit source, final GeneratorContext context, final ClassNode node) throws CompilationFailedException {
//                new JavaAwareResolveVisitor(JavaStubCompilationUnit.this).startResolving(node, source);
//            }
//        },Phases.CONVERSION);

        addPhaseOperation(new PrimaryClassNodeOperation()
        {
            @Override
            public void call(final SourceUnit source, final GeneratorContext context, final ClassNode node) throws CompilationFailedException {
                try {
                    stubGenerator.generateClass(node);
                    stubCount++;
                }
                catch (FileNotFoundException e) {
                    source.addException(e);
                }
            }
        },Phases.CONVERSION);
    }

    public JavaStubCompilationUnit(final CompilerConfiguration config, final GroovyClassLoader gcl) {
        this(config, gcl, null);
    }

    // Copied from groovy/core, trying to see how to fix import problems
//    public void gotoPhase(final int phase) throws CompilationFailedException {
//        super.gotoPhase(phase);
//
//        if (phase==Phases.SEMANTIC_ANALYSIS) {
//            Iterator modules = getAST().getModules().iterator();
//            while (modules.hasNext()) {
//                ModuleNode module = (ModuleNode) modules.next();
//                module.setImportsResolved(false);
//            }
//        }
//    }

    public int getStubCount() {
        return stubCount;
    }

    @Override
    public void compile() throws CompilationFailedException {
        stubCount = 0;
        super.compile(Phases.CONVERSION);
    }

    @Override
    public void configure(final CompilerConfiguration config) {
        super.configure(config);
        // GroovyClassLoader should be able to find classes compiled from java sources
        File targetDir = config.getTargetDirectory();
        if (targetDir != null) {
            final String classOutput = targetDir.getAbsolutePath();
            getClassLoader().addClasspath(classOutput);
        }
    }

    @Override
    public SourceUnit addSource(final File file) {
        if (file.getName().toLowerCase().endsWith(DOT_GROOVY)) {
            return super.addSource(file);
        }
        return null;
    }

    @Override
    public SourceUnit addSource(URL url) {
        if (url.getPath().toLowerCase().endsWith(DOT_GROOVY)) {
            return super.addSource(url);
        }
        return null;
    }
}

@@ -1105,125 +1105,8 @@
 it;%0A
-import org.codehaus.groovy.tools.javac.JavaAwareResolveVisitor;%0Aimport org.codehaus.groovy.tools.javac.JavaCompiler;%0A
 impo
@@ -1159,16 +1159,16 @@
 erator;%0A
+
 %0Aimport 
@@ -2149,458 +2149,8 @@
 );%0A%0A
-        // Copied from groovy/core, trying to see how to fix import problems%0A//        addPhaseOperation(new PrimaryClassNodeOperation()%0A//        %7B%0A//            public void call(final SourceUnit source, final GeneratorContext context, final ClassNode node) throws CompilationFailedException %7B%0A//                new JavaAwareResolveVisitor(JavaStubCompilationUnit.this).startResolving(node, source);%0A//            %7D%0A//        %7D,Phases.CONVERSION);%0A%0A
     
@@ -2816,83 +2816,8 @@
  %7D%0A%0A
-    // Copied from groovy/core, trying to see how to fix import problems%0A//
     
@@ -2891,18 +2891,16 @@
 ption %7B%0A
-//
         
@@ -2927,13 +2927,9 @@
 e);%0A
-//%0A//
+%0A
     
@@ -2967,26 +2967,90 @@
 ANALYSIS) %7B%0A
-//
+            // This appears to be needed to avoid missing imports%0A
             
@@ -3098,26 +3098,24 @@
 iterator();%0A
-//
             
@@ -3142,18 +3142,16 @@
 xt()) %7B%0A
-//
         
@@ -3207,18 +3207,16 @@
 next();%0A
-//
         
@@ -3257,18 +3257,16 @@
 false);%0A
-//
         
@@ -3267,26 +3267,24 @@
           %7D%0A
-//
         %7D%0A//
@@ -3281,18 +3281,16 @@
       %7D%0A
-//
     %7D%0A%0A 

Fix problem with resolving types, not really sure why this fixes it, but it does