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

/*Generated by MPS */

import org.jetbrains.mps.openapi.module.SModule;
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 org.jetbrains.mps.openapi.model.SModel;
import jetbrains.mps.util.IterableUtil;
import jetbrains.mps.internal.collections.runtime.Sequence;
import jetbrains.mps.smodel.SModelStereotype;

public class ModuleTestCollector extends TestCollector {
  private final SModule myModule;

  public ModuleTestCollector(@NotNull SModule module, @Nullable ProgressMonitor monitor, boolean breakOnFirstFound) {
    super(monitor, breakOnFirstFound);
    myModule = module;
  }

  @NotNull
  @Override
  public List<ITestNodeWrapper> collect() {
    List<ITestNodeWrapper> result = ListSequence.fromList(new ArrayList<ITestNodeWrapper>());
    Iterable<SModel> models = myModule.getModels();
    myMonitor.start("Fetching tests from module " + myModule.getModuleName(), IterableUtil.asCollection(models).size());
    try {
      for (SModel model : Sequence.fromIterable(models)) {
        if (!(SModelStereotype.isStubModel(model))) {
          if (myMonitor.isCanceled()) {
            return ListSequence.fromList(new ArrayList<ITestNodeWrapper>());
          }
          List<ITestNodeWrapper> modelTests = new ModelTestCollector(model, myMonitor.subTask(1), myBreakOnFirstFound).collect();
          ListSequence.fromList(result).addSequence(ListSequence.fromList(modelTests));
          if (myBreakOnFirstFound && ListSequence.fromList(modelTests).isNotEmpty()) {
            return result;
          }
        }
        myMonitor.advance(1);
      }
    } finally {
      myMonitor.done();
    }
    return result;
  }
}
