///|
/// An output of one side of a `MemoryPair`, other than text to send.
#derive(Eq, Debug)
pub(all) struct Event {
  role : Role
  output : Output
}

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

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

///|
/// A client state machine and a server state machine that an in-memory
/// transport connects. Each `Send` of one side goes to the other side, so the
/// protocol runs with no socket and no event loop. The value is immutable.
pub struct MemoryPair {
  priv client : ProtocolState
  priv server : ProtocolState
}

///|
/// Deliver the texts that `outputs` sends to the other side, and the texts
/// that the other side sends back, until no text is left. Give the outputs that
/// are not `Send`, in order, with their side.
fn MemoryPair::pump(
  self : MemoryPair,
  from : Role,
  outputs : Array[Output],
) -> (MemoryPair, Array[Event]) {
  let events = []
  let mut client = self.client
  let mut server = self.server
  let queue : Array[(Role, String)] = []
  let collect = (role : Role, outputs : Array[Output]) => {
    for output in outputs {
      match output {
        Send(text) => {
          let to = match role {
            Client => Server
            Server => Client
          }
          queue.push((to, text))
        }
        other => events.push({ role, output: other, })
      }
    }
  }
  collect(from, outputs)
  while queue.length() > 0 {
    let (to, text) = queue.remove(0)
    match to {
      Server => {
        let (next, out) = server.receive(text)
        server = next
        collect(Server, out)
      }
      Client => {
        let (next, out) = client.receive(text)
        client = next
        collect(Client, out)
      }
    }
  }
  ({ client, server, }, events)
}

///|
/// Connect a new client to a new server and run the handshake.
pub fn MemoryPair::connect() -> (MemoryPair, Array[Event]) {
  let (client, outputs) = ProtocolState::client()
  { client, server: ProtocolState::server(), }.pump(Client, outputs)
}

///|
/// The client state.
pub fn MemoryPair::client_state(self : MemoryPair) -> ProtocolState {
  self.client
}

///|
/// The server state.
pub fn MemoryPair::server_state(self : MemoryPair) -> ProtocolState {
  self.server
}

///|
/// Run `step` on the client state, deliver the texts, and give the events of
/// both sides.
pub fn MemoryPair::on_client(
  self : MemoryPair,
  step : (ProtocolState) -> (ProtocolState, Array[Output]) raise,
) -> (MemoryPair, Array[Event]) raise {
  let (client, outputs) = step(self.client)
  { ..self, client, }.pump(Client, outputs)
}

///|
/// Run `step` on the server state, deliver the texts, and give the events of
/// both sides.
pub fn MemoryPair::on_server(
  self : MemoryPair,
  step : (ProtocolState) -> (ProtocolState, Array[Output]) raise,
) -> (MemoryPair, Array[Event]) raise {
  let (server, outputs) = step(self.server)
  { ..self, server, }.pump(Server, outputs)
}

///|
/// Start a call on the client, deliver the texts, and give the IDs of the call
/// and the events of both sides.
pub fn MemoryPair::client_call(
  self : MemoryPair,
  mode : CallMode,
  target : MethodName,
  arguments : ArrayView[HubValue],
  uploads~ : Int32 = 0,
) -> (MemoryPair, Invoked, Array[Event]) raise UsageError {
  let (client, invoked, outputs) = self.client.call(
    mode,
    target,
    arguments,
    uploads~,
  )
  let (pair, events) = { ..self, client, }.pump(Client, outputs)
  (pair, invoked, events)
}