package jetbrains.mps.ide.depanalyzer.actions;

/*Generated by MPS */

import com.intellij.openapi.project.Project;
import jetbrains.mps.ide.depanalyzer.DependencyViewerScope;
import jetbrains.mps.plugins.projectplugins.ProjectPluginManager;
import org.jetbrains.annotations.NotNull;
import jetbrains.mps.project.MPSProject;
import org.jetbrains.mps.openapi.module.SModule;
import org.jetbrains.annotations.Nullable;
import jetbrains.mps.ide.findusages.model.SearchResults;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.ide.depanalyzer.ReferencesFinder;
import jetbrains.mps.progress.EmptyProgressMonitor;

public final class DependenciesUtil {
  private DependenciesUtil() {
  }

  public static void openDependenciesTool(Project ideaProject, DependencyViewerScope scope, boolean setActive) {
    AnalyzeDependencies_Tool tool = ideaProject.getComponent(ProjectPluginManager.class).getTool(AnalyzeDependencies_Tool.class);
    if (scope != null) {
      tool.setContent(scope, null, false);
    }
    tool.openToolLater(setActive);
  }

  /**
   * requires EDT
   */
  public static void openDependenciesTool(@NotNull MPSProject mpsProject, @NotNull SModule from, @Nullable SModule to, boolean meta) {
    AnalyzeDependencies_Tool tool = mpsProject.getProject().getComponent(ProjectPluginManager.class).getTool(AnalyzeDependencies_Tool.class);
    DependencyViewerScope fromScope = new DependencyViewerScope(mpsProject.getRepository());
    fromScope.add(from);
    DependencyViewerScope toScope = null;
    if (to != null) {
      toScope = new DependencyViewerScope(mpsProject.getRepository());
      toScope.add(to);
    }
    tool.setContent(fromScope, toScope, meta);
    tool.openToolLater(true);
  }

  /**
   * requires model read
   * at the moment, may run for a noticeable time without progress reporting. I'd like to fix this by stop fast once any external ref found, but
   * if I don't manage to do that, perhaps, shall pass ProgressMonitor here
   */
  public static boolean hasDependenciesToShow(MPSProject mpsProject, SModule from, SModule to) {
    DependencyViewerScope scopeFrom = new DependencyViewerScope(mpsProject.getRepository());
    scopeFrom.add(from);
    DependencyViewerScope scopeTo = new DependencyViewerScope(mpsProject.getRepository());
    scopeTo.add(to);
    // FIXME would be great to stop after first result to save the time
    SearchResults<SNode> refsBetweenScopes = new ReferencesFinder(scopeFrom).getRefsBetweenScopes(scopeFrom, scopeTo, new EmptyProgressMonitor());
    return !(refsBetweenScopes.getSearchResults2().isEmpty());
  }

}
