/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.jetbrains.plugins.groovy.lang.psi.impl.javaView;

import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElementFinder;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.stubs.GroovyShortNamesCache;

import java.util.Collection;
import java.util.List;

/**
 * @author ven
 */
public class GroovyClassFinder extends PsiElementFinder {
  private final GroovyShortNamesCache myCache;

  public GroovyClassFinder(Project project) {
    myCache = GroovyShortNamesCache.getGroovyShortNamesCache(project);
  }

  @Override
  @Nullable
  public PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
    final List<PsiClass> classes = myCache.getClassesByFQName(qualifiedName, scope, true);
    return classes.isEmpty() ? null : classes.get(0);
  }

  @Override
  @NotNull
  public PsiClass[] findClasses(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
    final Collection<PsiClass> classes = myCache.getClassesByFQName(qualifiedName, scope, true);
    return classes.isEmpty() ? PsiClass.EMPTY_ARRAY : classes.toArray(PsiClass.EMPTY_ARRAY);
  }

}

@@ -806,32 +806,108 @@
 psi.
-search.GlobalSearchScope
+PsiFile;%0Aimport com.intellij.psi.search.GlobalSearchScope;%0Aimport com.intellij.psi.util.PsiClassUtil
 ;%0Aim
@@ -985,24 +985,85 @@
 s.Nullable;%0A
+import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase;%0A
 import org.j
@@ -1150,16 +1150,75 @@
 ection;%0A
+import java.util.Collections;%0Aimport java.util.Comparator;%0A
 import j
@@ -1702,55 +1702,454 @@
     
-return classes.isEmpty() ? null : classes.get(0
+if (classes.isEmpty()) return null;%0A    if (classes.size() == 1) return classes.get(0);%0A    return Collections.min(classes, PsiClassUtil%0A      .createScopeComparator(scope)%0A      .thenComparing(c -%3E c.getQualifiedName(), Comparator.nullsLast(Comparator.naturalOrder()))%0A      .thenComparing(c -%3E %7B%0A        PsiFile file = c.getContainingFile();%0A        return file instanceof GroovyFileBase ? ((GroovyFileBase)file).getPackageName() : %22%22;%0A      %7D)
 );%0A 

make GroovyClassFinder.findClass predictable