///|
priv enum DispatchState {
  Pending
  Starting
  Ready
}

///|
/// State used to gate service dispatch independently of the process backend.
pub struct Schedule {
  graph : Graph
  priv states : Array[DispatchState]
  max_parallel : Int32
}

///|
pub fn Graph::schedule(self : Graph, max_parallel : Int32) -> Schedule {
  {
    graph: self,
    states: Array::make(self.nodes.length(), Pending),
    max_parallel: max_parallel.max(1),
  }
}

///|
/// Reserve currently eligible services in deterministic order. Ready services
/// release startup slots even though their processes continue running.
pub fn Schedule::dispatch(self : Schedule) -> Array[Int32] {
  let mut slots = self.max_parallel
  for state in self.states {
    if state is Starting {
      slots -= 1
    }
  }
  let selected : Array[Int32] = []
  for i in self.graph.sorted {
    if slots == 0 {
      break
    }
    if self.states[i] is Pending &&
      self.graph.incoming[i].all(fn(parent) { self.states[parent] is Ready }) {
      self.states[i] = Starting
      selected.push(i)
      slots -= 1
    }
  }
  selected
}

///|
pub fn Schedule::ready(self : Schedule, index : Int32) -> Unit {
  if self.states.get(index) is Some(Starting) {
    self.states[index] = Ready
  }
}

///|
pub fn Schedule::complete(self : Schedule) -> Bool {
  self.states.all(fn(state) { state is Ready })
}

///|
pub fn Schedule::has_dispatched(self : Schedule, index : Int32) -> Bool {
  self.states.get(index) is Some(Starting | Ready)
}