/*
 * Copyright 2000-2011 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 com.intellij.testAssistant;

import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

/**
 * @author yole
 */
public class TestDataLineMarkerProvider implements LineMarkerProvider {
  public LineMarkerInfo getLineMarkerInfo(PsiElement element) {
    return null;
  }

  private static boolean isTestMethod(@NotNull PsiMethod method) {
    if (isTestMethodWithAnnotation(method)) {
      return true;
    }

    final List<String> files = TestDataGuessByExistingFilesUtil.collectTestDataByExistingFiles(method);
    return files != null && !files.isEmpty();
  }

  private static boolean isTestMethodWithAnnotation(@NotNull PsiMethod method) {
    String name = method.getName();
    if (!name.startsWith("test")) {
      return false;
    }
    String testDataPath = getTestDataBasePath(method.getContainingClass());
    if (testDataPath == null) {
      return false;
    }
    List<String> fileNames = new TestDataReferenceCollector(testDataPath, name.substring(4)).collectTestDataReferences(method);
    return fileNames != null && !fileNames.isEmpty();
  }

  public void collectSlowLineMarkers(List<PsiElement> elements, Collection<LineMarkerInfo> result) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return;
    }
    for (PsiElement element : elements) {
      if (!(element instanceof PsiMethod)) {
        continue;
      }
      final PsiMethod method = (PsiMethod)element;
      if (isTestMethod(method)) {
        result.add(new LineMarkerInfo<PsiMethod>(
          method, method.getTextRange(), PlatformIcons.TEST_SOURCE_FOLDER, Pass.UPDATE_ALL, null, new TestDataNavigationHandler(),
          GutterIconRenderer.Alignment.LEFT
        ));
      }
    }
  }

  @Nullable
  public static String getTestDataBasePath(PsiClass psiClass) {
    final PsiAnnotation annotation = AnnotationUtil.findAnnotationInHierarchy(psiClass, Collections.singleton("com.intellij.testFramework.TestDataPath"));
    if (annotation != null) {
      final PsiAnnotationMemberValue value = annotation.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME);
      if (value instanceof PsiExpression) {
        final Project project = value.getProject();
        final PsiConstantEvaluationHelper evaluationHelper = JavaPsiFacade.getInstance(project).getConstantEvaluationHelper();
        final Object constantValue = evaluationHelper.computeConstantExpression(value, false);
        if (constantValue instanceof String) {
          String path = (String) constantValue;
          if (path.contains("$CONTENT_ROOT")) {
            final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
            final VirtualFile file = psiClass.getContainingFile().getVirtualFile();
            if (file == null) {
              return null;
            }
            final VirtualFile contentRoot = fileIndex.getContentRootForFile(file);
            if (contentRoot == null) return null;
            path = path.replace("$CONTENT_ROOT", contentRoot.getPath());
          }
          if (path.contains("$PROJECT_ROOT")) {
            final VirtualFile baseDir = project.getBaseDir();
            if (baseDir == null) {
              return null;
            }
            path = path.replace("$PROJECT_ROOT", baseDir.getPath());
          }
          return path;
        }
      }
    }
    return null;
  }

}

@@ -1546,24 +1546,493 @@
  element) %7B%0A
+    if (ApplicationManager.getApplication().isUnitTestMode()) %7B%0A      return null;%0A    %7D%0A    if (element instanceof PsiMethod) %7B%0A      final PsiMethod method = (PsiMethod)element;%0A      if (isTestMethod(method)) %7B%0A        return new LineMarkerInfo%3CPsiMethod%3E(%0A          method, method.getModifierList().getTextRange(), PlatformIcons.TEST_SOURCE_FOLDER, Pass.UPDATE_ALL, null, new TestDataNavigationHandler(),%0A          GutterIconRenderer.Alignment.LEFT);%0A      %7D%0A    %7D%0A
     return n
@@ -2940,541 +2940,8 @@
 ) %7B%0A
-    if (ApplicationManager.getApplication().isUnitTestMode()) %7B%0A      return;%0A    %7D%0A    for (PsiElement element : elements) %7B%0A      if (!(element instanceof PsiMethod)) %7B%0A        continue;%0A      %7D%0A      final PsiMethod method = (PsiMethod)element;%0A      if (isTestMethod(method)) %7B%0A        result.add(new LineMarkerInfo%3CPsiMethod%3E(%0A          method, method.getTextRange(), PlatformIcons.TEST_SOURCE_FOLDER, Pass.UPDATE_ALL, null, new TestDataNavigationHandler(),%0A          GutterIconRenderer.Alignment.LEFT%0A        ));%0A      %7D%0A    %7D%0A
   %7D%0A

fix test line markers