///|
/// The delays of a schedule before the count limit.
#derive(Eq, Debug)
priv enum Delays {
  Fixed(@lander_core.TimeLimit)
  /// Each delay is twice the previous one, and at most the maximum.
  Doubling(first~ : @lander_core.TimeLimit, maximum~ : @lander_core.TimeLimit)
}

///|
/// An immutable sequence of delays for repeated sends. Each delay starts after
/// the previous message is admitted. Without `up_to`, the sequence has no end.
/// A schedule holds no clock and no state, so a test can list its delays.
#derive(Eq, Debug)
pub struct Schedule {
  priv form : Delays
  priv count : MessageCount?
}

///|
pub extend Schedule with Eq::{equal, not_equal}

///|
pub extend Schedule with @debug.Debug::{to_repr}

///|
/// The same delay each time.
pub fn Schedule::fixed_delay(delay : @lander_core.TimeLimit) -> Schedule {
  { form: Fixed(delay), count: None, }
}

///|
/// A delay that starts at `first`, doubles each time and stays at `maximum`.
/// When `first` is more than `maximum`, each delay is `maximum`.
pub fn Schedule::exponential(
  first~ : @lander_core.TimeLimit,
  maximum~ : @lander_core.TimeLimit,
) -> Schedule {
  { form: Doubling(first=minimum(first, maximum), maximum~), count: None, }
}

///|
/// The same delays, for at most `count` sends. A second limit can only make
/// the schedule shorter.
pub fn Schedule::up_to(self : Schedule, count : MessageCount) -> Schedule {
  let count = match self.count {
    Some(earlier) if earlier.value < count.value => earlier
    _ => count
  }
  { ..self, count: Some(count), }
}

///|
/// The delays in their order, as a new iterator. It has no end when the
/// schedule has no count limit, so take a part of it with `take`.
pub fn Schedule::delays(self : Schedule) -> Iter[@lander_core.TimeLimit] {
  let delays = match self.form {
    Fixed(delay) => Iter::repeat(delay)
    Doubling(first~, maximum~) => {
      let mut next = first
      Iter(() => {
        let delay = next
        next = doubled(delay, maximum)
        Some(delay)
      })
    }
  }
  match self.count {
    Some(count) => delays.take(count.value)
    None => delays
  }
}

///|
fn minimum(
  left : @lander_core.TimeLimit,
  right : @lander_core.TimeLimit,
) -> @lander_core.TimeLimit {
  if left <= right {
    left
  } else {
    right
  }
}

///|
/// Twice `delay`, or `maximum` when that is less. The comparison comes before
/// the multiplication, so the result stays in the range of a time limit.
fn doubled(
  delay : @lander_core.TimeLimit,
  maximum : @lander_core.TimeLimit,
) -> @lander_core.TimeLimit {
  let millis = delay.to_millis()
  if millis > maximum.to_millis() - millis {
    return maximum
  }
  @lander_core.TimeLimit::millis(millis * 2) catch {
    _ => abort("a delay below the maximum is a valid time limit")
  }
}