// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.api;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPolyVariantReference;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.Collection;

/**
 * Same as {@link PsiPolyVariantReference} but returns {@link GroovyResolveResult}.
 */
public interface GroovyReference extends PsiPolyVariantReference {

  GroovyReference[] EMPTY_ARRAY = new GroovyReference[0];

  @Nullable
  @Override
  default PsiElement resolve() {
    return advancedResolve().getElement();
  }

  @NotNull
  default GroovyResolveResult advancedResolve() {
    GroovyResolveResult[] results = multiResolve(false);
    return results.length == 1 ? results[0] : EmptyGroovyResolveResult.INSTANCE;
  }

  /**
   * Either this or {@link #resolve(boolean)} must be implemented.
   */
  @NotNull
  @Override
  default GroovyResolveResult[] multiResolve(boolean incompleteCode) {
    return resolve(incompleteCode).toArray(GroovyResolveResult.EMPTY_ARRAY);
  }

  /**
   * Either this or {@link #multiResolve(boolean)} must be implemented.
   *
   * @param incomplete if true, the code in the context of which the reference is being resolved is considered incomplete,
   *                   and the method may return additional invalid results.
   * @return read-only collection of results
   */
  @NotNull
  default Collection<? extends GroovyResolveResult> resolve(boolean incomplete) {
    return Arrays.asList(multiResolve(incomplete));
  }
}

@@ -18,9 +18,9 @@
 -201
-8
+9
  Jet
@@ -412,16 +412,88 @@
 ction;%0A%0A
+import static com.intellij.util.containers.ContainerUtil.getFirstItem;%0A%0A
 /**%0A * S
@@ -873,16 +873,37 @@
 ) %7B%0A    
+Collection%3C? extends 
 GroovyRe
@@ -913,18 +913,17 @@
 veResult
-%5B%5D
+%3E
  results
@@ -925,22 +925,17 @@
 sults = 
-multiR
+r
 esolve(f
@@ -949,23 +949,20 @@
     
-return 
+if (
 results.
 leng
@@ -961,34 +961,88 @@
 lts.
-length == 1 ? results%5B0%5D :
+size() == 1) %7B%0A      return getFirstItem(results);%0A    %7D%0A    else %7B%0A      return
  Emp
@@ -1073,16 +1073,22 @@
 STANCE;%0A
+    %7D%0A
   %7D%0A%0A  /

implement GroovyReference#advancedResolve via #resolve(boolean)