package jetbrains.mps.baseLanguage.unitTest.execution.settings;

/*Generated by MPS */

import org.jetbrains.mps.openapi.model.SModel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.util.ProgressMonitor;
import java.util.List;
import jetbrains.mps.baseLanguage.unitTest.execution.client.ITestNodeWrapper;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import java.util.ArrayList;
import java.util.Collection;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.util.IterableUtil;
import jetbrains.mps.internal.collections.runtime.CollectionSequence;
import jetbrains.mps.baseLanguage.unitTest.execution.client.TestNodeWrapperFactory;

public class ModelTestCollector extends TestCollector {
  private final SModel myModel;

  public ModelTestCollector(@NotNull SModel model, @Nullable ProgressMonitor monitor, boolean breakOnFirstFound) {
    super(monitor, breakOnFirstFound);
    myModel = model;
  }

  @NotNull
  @Override
  public List<ITestNodeWrapper> collect() {
    List<ITestNodeWrapper> result = ListSequence.fromList(new ArrayList<ITestNodeWrapper>());
    Collection<SNode> roots = IterableUtil.asCollection(myModel.getRootNodes());
    myMonitor.start("model " + myModel.getName(), roots.size());
    try {
      for (SNode root : CollectionSequence.fromCollection(roots)) {
        if (myMonitor.isCanceled()) {
          return ListSequence.fromList(new ArrayList<ITestNodeWrapper>());
        }
        ITestNodeWrapper wrappedNode = TestNodeWrapperFactory.tryToWrap(root);
        if (wrappedNode != null) {
          ListSequence.fromList(result).addElement(wrappedNode);
          if (myBreakOnFirstFound) {
            return result;
          }
        }
        myMonitor.advance(1);
      }
    } finally {
      myMonitor.done();
    }
    return result;
  }
}
