///|
/// A call to clients that a handler sent.
#derive(Eq, Debug)
pub(all) struct Sent {
  target : Target
  method_ : @signalr.MethodName
  arguments : Array[@signalr.HubValue]
}

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

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

///|
/// A change of a group that a handler made.
#derive(Eq, Debug)
pub(all) enum GroupChange {
  Added(@signalr.ConnectionId, @signalr.GroupName)
  Removed(@signalr.ConnectionId, @signalr.GroupName)
}

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

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

///|
/// A hub context for a unit test of a handler. It records the calls to clients
/// and the group changes, with no connection, no actor and no event loop.
pub struct Recorder {
  priv sent : Array[Sent]
  priv group_changes : Array[GroupChange]
  priv results : Array[@signalr.Outcome]
  priv uploads : Map[@signalr.StreamId, Array[@signalr.HubValue]]
}

///|
/// A recorder. `results` are the replies of the client to each call that waits
/// for a result, in order; when no reply is left, the connection has ended.
/// `uploads` are the items of the upload streams of the call.
pub fn Recorder::new(
  results~ : Array[@signalr.Outcome] = [],
  uploads~ : Array[(@signalr.StreamId, Array[@signalr.HubValue])] = [],
) -> Recorder {
  let streams = Map([])
  for upload in uploads {
    streams[upload.0] = upload.1.copy()
  }
  { sent: [], group_changes: [], results: results.copy(), uploads: streams, }
}

///|
/// The context for a call of `connection_id`.
pub fn Recorder::context(
  self : Recorder,
  connection_id : @signalr.ConnectionId,
  identity~ : @signalr.Identity = @signalr.Identity::anonymous(),
) -> HubContext {
  let backend = Backend::new(
    send=(target, method_, arguments) => {
      self.sent.push({ target, method_, arguments, })
    },
    invoke=(id, method_, arguments) => {
      self.sent.push({
        target: Connections(ReadOnlyArray::from_array([id])),
        method_,
        arguments,
      })
      guard !self.results.is_empty() else { raise Disconnected(id) }
      self.results.remove(0)
    },
    join=(id, group) => self.group_changes.push(Added(id, group)),
    leave=(id, group) => self.group_changes.push(Removed(id, group)),
    read_upload=stream => {
      match self.uploads.get(stream) {
        Some(items) if !items.is_empty() => Some(items.remove(0))
        _ => None
      }
    },
  )
  HubContext::new(
    connection_id,
    identity,
    backend,
    uploads=ReadOnlyArray::from_iter(self.uploads.keys()),
  )
}

///|
/// The calls to clients, in order.
pub fn Recorder::sent(self : Recorder) -> Array[Sent] {
  self.sent.copy()
}

///|
/// The group changes, in order.
pub fn Recorder::group_changes(self : Recorder) -> Array[GroupChange] {
  self.group_changes.copy()
}