///|
/// What a connection must do now for its time limits.
#derive(Eq, Debug)
pub(all) enum TimerAction {
  /// Nothing until the time `until`, in the clock's milliseconds.
  WaitUntil(Int64)
  /// The endpoint sent nothing for the keep-alive interval: send a Ping.
  SendPing
  /// The peer sent nothing for the timeout: end the connection.
  TimedOut
  /// The peer sent no complete handshake in the handshake timeout.
  HandshakeTimedOut
}

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

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

///|
/// The keep-alive state of one connection, on a clock that the caller gives as
/// milliseconds (design SRV-3). The value is immutable, so tests use any times
/// and need no real clock.
#derive(Eq, Debug)
pub struct KeepAlive {
  priv interval : TimeLimit
  priv timeout : TimeLimit
  priv handshake_timeout : TimeLimit
  priv opened_at : Int64
  priv handshake_done : Bool
  priv last_sent : Int64
  priv last_received : Int64
}

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

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

///|
/// The state of a connection that opened at `now`.
pub fn KeepAlive::new(
  now : Int64,
  interval~ : TimeLimit = TimeLimit::default_keep_alive(),
  timeout~ : TimeLimit = TimeLimit::default_client_timeout(),
  handshake_timeout~ : TimeLimit = TimeLimit::default_handshake_timeout(),
) -> KeepAlive {
  {
    interval,
    timeout,
    handshake_timeout,
    opened_at: now,
    handshake_done: false,
    last_sent: now,
    last_received: now,
  }
}

///|
/// The endpoint sent a message at `now`.
pub fn KeepAlive::sent(self : KeepAlive, now : Int64) -> KeepAlive {
  { ..self, last_sent: now, }
}

///|
/// The peer sent a message at `now`.
pub fn KeepAlive::received(self : KeepAlive, now : Int64) -> KeepAlive {
  { ..self, last_received: now, }
}

///|
/// The handshake completed at `now`.
pub fn KeepAlive::handshake_completed(
  self : KeepAlive,
  now : Int64,
) -> KeepAlive {
  { ..self, handshake_done: true, last_received: now, }
}

///|
/// The action at `now`. A timeout comes before a Ping.
pub fn KeepAlive::action(self : KeepAlive, now : Int64) -> TimerAction {
  if !self.handshake_done {
    let deadline = self.opened_at + self.handshake_timeout.to_milliseconds()
    return if now >= deadline { HandshakeTimedOut } else { WaitUntil(deadline) }
  }
  let timeout_at = self.last_received + self.timeout.to_milliseconds()
  if now >= timeout_at {
    return TimedOut
  }
  let ping_at = self.last_sent + self.interval.to_milliseconds()
  if now >= ping_at {
    return SendPing
  }
  WaitUntil(if ping_at < timeout_at { ping_at } else { timeout_at })
}