package jetbrains.mps.progress;

/*Generated by MPS */

import jetbrains.mps.annotations.GeneratedClass;
import org.jetbrains.mps.openapi.util.ProgressMonitor;
import java.util.Collection;

@GeneratedClass(node = "r:37761ffb-9538-49ac-a331-c8121d2c14b2(jetbrains.mps.progress)/4352906377363159179", model = "r:37761ffb-9538-49ac-a331-c8121d2c14b2(jetbrains.mps.progress)")
public class DefaultTaskScheduler implements TaskScheduler {

  @Override
  public IdleWork schedule(final ProgressTask task, final ProgressMonitor monitor) {
    return IdleWork.Support.run(() -> runAndWait(task, monitor));
  }

  @Override
  public IdleWork scheduleSequential(final Collection<ProgressTask> tasks, final ProgressMonitor monitor) {
    return IdleWork.Support.run(() -> {
      boolean success = true;
      for (ProgressTask task : tasks) {
        runAndWait(task, monitor);
        // FIXME reimplement cancellation
        if (!(success)) {
          break;
        }
      }
    });
  }

  @Override
  public IdleWork scheduleParallel(Collection<ProgressTask> tasks, ProgressMonitor monitor) {
    return scheduleSequential(tasks, monitor);
  }

  private void runAndWait(ProgressTask task, ProgressMonitor monitor) {
    try {
      // FIXME track task state
      task.initMonitor(monitor);
      if (task.isReady()) {
        IdleWork work = task.schedule(this);
        work.finish();
        task.onSuccess();
      } else {
        task.onCancel();
      }
    } catch (Throwable err) {
      task.onThrowable(err);
    } finally {
      task.onFinished();
    }
  }

}
