package jetbrains.mps.ide.editor.util;

/*Generated by MPS */

import jetbrains.mps.annotations.GeneratedClass;
import com.intellij.openapi.progress.Task;
import jetbrains.mps.project.MPSProject;
import jetbrains.mps.ide.findusages.model.SearchQuery;
import java.util.List;
import jetbrains.mps.ide.findusages.findalgorithm.finders.IFinder;
import org.jetbrains.annotations.NotNull;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import jetbrains.mps.ide.findusages.model.SearchResult;
import com.intellij.openapi.progress.ProgressIndicator;
import jetbrains.mps.progress.ProgressMonitorAdapter;
import jetbrains.mps.ide.findusages.view.FindUtils;

@GeneratedClass(node = "r:4e6037e6-9135-44f8-9403-04d79fc40f4a(jetbrains.mps.ide.editor.util)/7052698666283512227", model = "r:4e6037e6-9135-44f8-9403-04d79fc40f4a(jetbrains.mps.ide.editor.util)")
public abstract class BackgroundSearchTask extends Task.Backgroundable {
  private final MPSProject myMPSProject;
  private final SearchQuery myQuery;
  private final List<IFinder> myFinders;
  private volatile boolean myCancelled = false;

  /*package*/ BackgroundSearchTask(@NotNull MPSProject project, @NotNull SearchQuery query, @NotNull List<IFinder> finders, @NotNull String title) {
    super(project.getProject(), title, true, PerformInBackgroundOption.ALWAYS_BACKGROUND);
    myMPSProject = project;
    myQuery = query;
    myFinders = finders;
  }

  @Override
  public void onCancel() {
    myCancelled = true;
  }

  public boolean isCancelled() {
    return myCancelled;
  }

  public abstract void onUsageFound(@NotNull SearchResult<?> result);

  @Override
  public void run(@NotNull final ProgressIndicator indicator) {
    myMPSProject.getRepository().getModelAccess().runReadAction(new Runnable() {
      @Override
      public void run() {
        IFinder.FindCallback callback = new IFinder.FindCallback() {
          @Override
          public void onUsageFound(@NotNull SearchResult<?> result) {
            BackgroundSearchTask.this.onUsageFound(result);
          }
        };
        ProgressMonitorAdapter monitor = new ProgressMonitorAdapter(indicator) {
          @Override
          public boolean isCanceled() {
            return super.isCanceled() || isCancelled();
          }
        };
        FindUtils.searchForResults(monitor, callback, myQuery, myFinders.toArray(new IFinder[0]));
      }
    });
  }
}
