///|
/// A point in time, as whole milliseconds of a clock that does not go back. Only
/// the difference of two points of one clock has a meaning.
#derive(Eq, Compare, Debug)
pub struct Instant {
  priv millis : Int64
}

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

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

///|
/// Make a point in time from the milliseconds of a clock.
pub fn Instant::millis(count : Int64) -> Instant {
  { millis: count, }
}

///|
/// The milliseconds of the clock.
pub fn Instant::to_millis(self : Instant) -> Int64 {
  self.millis
}

///|
/// The time from `start` to `self`, and zero when `self` is earlier.
fn Instant::since(self : Instant, start : Instant) -> Uptime {
  let millis = self.millis - start.millis
  { millis: if millis < 0 { 0 } else { millis.reinterpret_as_uint64() }, }
}

///|
/// The time limit of each call, and whether the transport enforces it.
#derive(Eq, Debug)
pub(all) struct CallLimit {
  limit : @lander_core.TimeLimit
  enforcement : Enforcement
}

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

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

///|
/// A call that gave its response after the limit, because nothing can end it.
#derive(Eq, Debug)
pub struct LateCall {
  operation : Operation
  limit : @lander_core.TimeLimit
  elapsed : Uptime
}

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

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

///|
fn CallLimit::late(
  self : CallLimit,
  operation : Operation,
  elapsed : Uptime,
) -> LateCall? {
  if self.enforcement is NotEnforced &&
    elapsed.millis > self.limit.to_millis().to_uint64() {
    Some({ operation, limit: self.limit, elapsed, })
  } else {
    None
  }
}

///|
/// The start of a plugin: `describe`, and then `start` with the settings.
pub struct Launch {
  priv limit : CallLimit
  priv settings : Bytes
  priv since : Instant
  priv description : Description?
}

///|
/// The step that follows a response during the start. The last part is present when
/// the call before it was late.
pub enum LaunchStep {
  /// Make this call at once.
  Call(Launch, Request, LateCall?)
  /// The plugin started.
  Started(Session, LateCall?)
  /// The plugin cannot start. Make no more calls.
  Refused(PluginFailure, LateCall?)
}

///|
/// Begin the start of a plugin. Make the call that this function gives at once, and
/// pass its response to `Launch::answered`.
pub fn Launch::new(
  now : Instant,
  limit : CallLimit,
  settings : Bytes,
) -> (Launch, Request) {
  ({ limit, settings, since: now, description: None, }, Describe)
}

///|
/// The operation of the call in progress.
fn Launch::operation(self : Launch) -> Operation {
  if self.description is None {
    Describe
  } else {
    Start
  }
}

///|
/// Take the response of the call in progress.
pub fn Launch::answered(
  self : Launch,
  now : Instant,
  response : Response,
) -> LaunchStep {
  let operation = self.operation()
  let late = self.limit.late(operation, now.since(self.since))
  let reply = Reply::decode(operation, response) catch {
    error => return Refused(BrokenContract(operation~, error~), late)
  }
  match (reply, self.description) {
    (Described(description), _) =>
      Call(
        { ..self, since: now, description: Some(description), },
        Start(self.settings),
        late,
      )
    (Next(next), Some(description)) => {
      let session : Session = {
        description,
        limit: self.limit,
        started: now,
        arrivals: 0,
        waiting: @sorted_map.SortedMap([]),
        due: None,
        phase: Open(None),
      }
      // No event waits yet, so there are no actions.
      Started(session.follow(now, next).0, late)
    }
    (Failed(message), _) => Refused(Reported(operation~, message~), late)
    // `Reply::decode` gives no other reply for `describe` and `start`.
    (Next(_) | Handled(_, _) | Stopped | Rejected(_), _) =>
      Refused(Reported(operation~, message="unexpected reply"), late)
  }
}

///|
/// The failure of the plugin when the call in progress gave no response.
pub fn Launch::broken(self : Launch, fault : TransportFault) -> PluginFailure {
  NoResponse(operation=Some(self.operation()), fault~)
}

///|
/// The identity of one event that the application sent.
#derive(Eq, Hash, Debug)
pub struct Ticket {
  priv arrival : UInt64
}

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

///|
pub extend Ticket with Hash::{hash, hash_combine}

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

///|
/// What the host must do, in the order of the array.
#derive(Eq, Debug)
pub(all) enum Action {
  /// Give the reply bytes to the sender of the ticket.
  Answer(Ticket, Bytes)
  /// Give the error to the sender of the ticket.
  Refuse(Ticket, SendError)
  /// Write a warning for the late call.
  Warn(LateCall)
  /// Write the failure to the log, and stop the host with exit code 1.
  Fail(PluginFailure)
}

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

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

///|
/// How a session ended.
#derive(Eq, Debug)
pub enum End {
  /// The plugin gave the next step `Finished`.
  Finished
  /// The plugin completed `stop`, or the host released it.
  Stopped
  /// The plugin failed.
  Failed(PluginFailure)
}

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

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

///|
/// One piece of work that waits for its turn.
priv enum Work {
  Event(EventName, Bytes)
  /// A tick. `asked` is true when the plugin asked for it with a wake request, so
  /// a later next step does not remove it.
  Tick(asked~ : Bool)
}

///|
/// The call in progress.
priv struct Current {
  since : Instant
  purpose : Purpose
}

///|
priv enum Purpose {
  ForEvent(Ticket, EventName)
  ForTick
}

///|
priv enum Phase {
  /// The plugin takes events.
  Open(Current?)
  /// The host asked for a stop. The `stop` call follows the call in progress.
  Draining(Current?, StopReason)
  /// The `stop` call is in progress since this time.
  Stopping(Instant)
  Ended(End)
}

///|
/// A plugin after its start. The session holds the contract rules: one call at a
/// time, the arrival order, the next step and the failures. It is a value with no
/// clock and no I/O. Each function gives a new session, and some functions also give
/// actions for the host.
///
/// The host makes the calls: it asks `next_call` for the next one, makes it, and
/// passes the response to `answered`. When there is no call, it waits until
/// `next_time` or until the session changes. When `end` gives a value, the host
/// releases the plugin.
pub struct Session {
  priv description : Description
  priv limit : CallLimit
  priv started : Instant
  /// The number of events and ticks that arrived.
  priv arrivals : UInt64
  /// The waiting work in arrival order. It holds at most one tick.
  priv waiting : @sorted_map.SortedMap[UInt64, Work]
  /// The time when the next tick arrives.
  priv due : Instant?
  priv phase : Phase
}

///|
/// What the plugin says about itself.
pub fn Session::description(self : Session) -> Description {
  self.description
}

///|
/// How the session ended, or `None` while it is active.
pub fn Session::end(self : Session) -> End? {
  match self.phase {
    Ended(end) => Some(end)
    _ => None
  }
}

///|
/// The time of the next tick, when the host must ask for the next call. It is `None`
/// while a call is in progress and when the plugin asked for no tick.
pub fn Session::next_time(self : Session) -> Instant? {
  match self.phase {
    Open(None) => self.due
    _ => None
  }
}

///|
/// Take the next call. The call is in progress from this time, so the host must make
/// it at once and pass its response to `answered` or its fault to `broken`. It is
/// `None` when a call is in progress and when no work waits.
pub fn Session::next_call(self : Session, now : Instant) -> (Session, Request?) {
  match self.phase {
    Draining(None, reason) =>
      ({ ..self, phase: Stopping(now), }, Some(Stop(reason)))
    Open(None) => {
      let session = self.settle(now)
      guard session.waiting.iter().head() is Some((arrival, work)) else {
        return (session, None)
      }
      let (purpose, request) : (Purpose, Request) = match work {
        Event(event, payload) =>
          (ForEvent({ arrival, }, event), Handle(event, payload))
        Tick(_) => (ForTick, Tick(now.since(session.started)))
      }
      (
        {
          ..session,
          waiting: session.waiting.remove(arrival),
          phase: Open(Some({ since: now, purpose, })),
        },
        Some(request),
      )
    }
    Open(Some(_)) | Draining(Some(_), _) | Stopping(_) | Ended(_) =>
      (self, None)
  }
}

///|
/// Send an event. The ticket names the sender in a later `Answer` or `Refuse`. An
/// event that the plugin cannot get raises at once and changes nothing.
pub fn Session::send(
  self : Session,
  now : Instant,
  event : EventName,
  payload : Bytes,
) -> (Session, Ticket) raise SendError {
  guard self.description.accepts(event) else { raise UnknownEvent(event) }
  match self.phase {
    Open(_) => ()
    Draining(_, _) | Stopping(_) | Ended(Stopped) => raise PluginStopped
    Ended(Finished) => raise PluginFinished
    Ended(Failed(failure)) => raise PluginFailed(failure)
  }
  let session = self.settle(now)
  let ticket = { arrival: session.arrivals, }
  (session.arrive(Event(event, payload)), ticket)
}

///|
/// Take back an event that still waits, because its sender is gone. When the
/// plugin already has the event, the call continues, and the host ignores the
/// later `Answer` or `Refuse`.
pub fn Session::withdraw(self : Session, ticket : Ticket) -> Session {
  { ..self, waiting: self.waiting.remove(ticket.arrival), }
}

///|
/// The plugin asked for a tick without a wait. A later next step does not remove
/// this tick.
pub fn Session::wake(self : Session, now : Instant) -> Session {
  guard self.phase is Open(_) else { return self }
  let session = self.settle(now)
  match session.waiting_tick() {
    Some(arrival) =>
      { ..session, waiting: session.waiting.insert(arrival, Tick(asked=true)), }
    None => session.arrive(Tick(asked=true))
  }
}

///|
/// Stop the plugin. The waiting events fail at their senders, the call in progress
/// ends, and then `next_call` gives `stop`.
pub fn Session::stop(
  self : Session,
  reason : StopReason,
) -> (Session, Array[Action]) {
  guard self.phase is Open(current) else { return (self, []) }
  (self.close(Draining(current, reason)), self.refusals(PluginStopped))
}

///|
/// The host released the plugin before the session ended, so there are no more calls
/// and no more responses. The sender of the call in progress and the waiting senders
/// get `PluginStopped`.
pub fn Session::released(self : Session) -> (Session, Array[Action]) {
  guard !(self.phase is Ended(_)) else { return (self, []) }
  (self.close(Ended(Stopped)), self.all_refusals(PluginStopped))
}

///|
/// Take the response of the call in progress. With no call in progress, nothing
/// changes.
pub fn Session::answered(
  self : Session,
  now : Instant,
  response : Response,
) -> (Session, Array[Action]) {
  guard self.in_progress() is Some((operation, since)) else {
    return (self, [])
  }
  let actions = late_actions(self.limit.late(operation, now.since(since)))
  let reply = Reply::decode(operation, response) catch {
    error => {
      let (session, more) = self.fail(BrokenContract(operation~, error~))
      return (session, actions + more)
    }
  }
  let session = self.settle(now)
  let (session, more) = match (reply, session.phase) {
    (Failed(message), _) => session.fail(Reported(operation~, message~))
    (Handled(next, reply), phase) => {
      if phase.sender() is Some((ticket, _)) {
        actions.push(Answer(ticket, reply))
      }
      session.follow(now, next)
    }
    (Rejected(message), phase) => {
      if phase.sender() is Some((ticket, event)) {
        actions.push(Refuse(ticket, RejectedEvent(event~, message~)))
      }
      (session.idle(), [])
    }
    (Next(next), _) => session.follow(now, next)
    (Stopped | Described(_), _) => (session.close(Ended(Stopped)), [])
  }
  (session, actions + more)
}

///|
/// The transport lost the plugin, during a call or between two calls.
pub fn Session::broken(
  self : Session,
  fault : TransportFault,
) -> (Session, Array[Action]) {
  guard !(self.phase is Ended(_)) else { return (self, []) }
  self.fail(
    NoResponse(operation=self.in_progress().map(call => call.0), fault~),
  )
}

///|
fn late_actions(late : LateCall?) -> Array[Action] {
  match late {
    Some(late) => [Warn(late)]
    None => []
  }
}

///|
fn Purpose::operation(self : Purpose) -> Operation {
  match self {
    ForEvent(_, _) => Handle
    ForTick => Tick
  }
}

///|
/// The sender that waits for the call in progress.
fn Phase::sender(self : Phase) -> (Ticket, EventName)? {
  match self {
    Open(Some({ purpose: ForEvent(ticket, event), .. }))
    | Draining(Some({ purpose: ForEvent(ticket, event), .. }), _) =>
      Some((ticket, event))
    _ => None
  }
}

///|
/// The call in progress, with its start time.
fn Session::in_progress(self : Session) -> (Operation, Instant)? {
  match self.phase {
    Open(Some(current)) | Draining(Some(current), _) =>
      Some((current.purpose.operation(), current.since))
    Stopping(since) => Some((Stop, since))
    Open(None) | Draining(None, _) | Ended(_) => None
  }
}

///|
/// Put work at the end of the arrival order.
fn Session::arrive(self : Session, work : Work) -> Session {
  {
    ..self,
    arrivals: self.arrivals + 1,
    waiting: self.waiting.insert(self.arrivals, work),
  }
}

///|
fn Session::waiting_tick(self : Session) -> UInt64? {
  for arrival, work in self.waiting {
    if work is Tick(..) {
      return Some(arrival)
    }
  }
  None
}

///|
/// Let the tick arrive when its time came.
fn Session::settle(self : Session, now : Instant) -> Session {
  guard self.due is Some(due) && due <= now else { return self }
  let session = { ..self, due: None, }
  // One tick answers the due time and a wake request.
  if session.waiting_tick() is Some(_) {
    session
  } else {
    session.arrive(Tick(asked=false))
  }
}

///|
/// The session after the end of its call, with the same next step.
fn Session::idle(self : Session) -> Session {
  let phase = match self.phase {
    Open(_) => Open(None)
    Draining(_, reason) => Draining(None, reason)
    phase => phase
  }
  { ..self, phase, }
}

///|
/// Apply the next step of a successful call. It replaces the earlier one, also when
/// the tick of the earlier one already waits.
fn Session::follow(
  self : Session,
  now : Instant,
  next : NextStep,
) -> (Session, Array[Action]) {
  if next is Finished {
    return (self.close(Ended(Finished)), self.refusals(PluginFinished))
  }
  let waiting = match self.waiting_tick() {
    Some(arrival) if self.waiting.get(arrival) is Some(Tick(asked=false)) =>
      self.waiting.remove(arrival)
    _ => self.waiting
  }
  let due : Instant? = match (next, self.phase) {
    (Wake(after), Open(_)) =>
      Some({ millis: now.millis + after.to_millis().to_int64(), })
    _ => None
  }
  ({ ..self, waiting, due, }.idle(), [])
}

///|
/// The refusals of the events that wait.
fn Session::refusals(self : Session, error : SendError) -> Array[Action] {
  let actions = []
  for arrival, work in self.waiting {
    if work is Event(_, _) {
      actions.push(Action::Refuse({ arrival, }, error))
    }
  }
  actions
}

///|
/// The session with no waiting work, in a phase that takes no events.
fn Session::close(self : Session, phase : Phase) -> Session {
  { ..self, waiting: @sorted_map.SortedMap([]), due: None, phase, }
}

///|
fn Session::fail(
  self : Session,
  failure : PluginFailure,
) -> (Session, Array[Action]) {
  let actions : Array[Action] = [Fail(failure)]
  (
    self.close(Ended(Failed(failure))),
    actions + self.all_refusals(PluginFailed(failure)),
  )
}

///|
/// The refusals of the event in progress and of the events that wait.
fn Session::all_refusals(self : Session, error : SendError) -> Array[Action] {
  let first : Array[Action] = match self.phase.sender() {
    Some((ticket, _)) => [Refuse(ticket, error)]
    None => []
  }
  first + self.refusals(error)
}