///|
/// A failure of a call to one client that waits for a result.
#derive(Eq, Debug)
pub(all) suberror ClientCallError {
  /// The connection ended before the client gave the result.
  Disconnected(@signalr.ConnectionId)
  /// The client replied with this error text.
  ClientFailed(String)
}

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

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

///|
/// The operations behind a hub context. The hub runtime and `Recorder` each
/// give one; a program does not need to make one.
pub struct Backend {
  priv send : async (Target, @signalr.MethodName, Array[@signalr.HubValue]) -> Unit
  priv invoke : async (
    @signalr.ConnectionId,
    @signalr.MethodName,
    Array[@signalr.HubValue],
  ) -> @signalr.Outcome
  priv join : async (@signalr.ConnectionId, @signalr.GroupName) -> Unit
  priv leave : async (@signalr.ConnectionId, @signalr.GroupName) -> Unit
  priv read_upload : async (@signalr.StreamId) -> @signalr.HubValue?
}

///|
/// A backend from its operations. `invoke` raises `Disconnected` when the
/// connection ends first.
pub fn Backend::new(
  send~ : async (Target, @signalr.MethodName, Array[@signalr.HubValue]) -> Unit,
  invoke~ : async (
    @signalr.ConnectionId,
    @signalr.MethodName,
    Array[@signalr.HubValue],
  ) -> @signalr.Outcome,
  join~ : async (@signalr.ConnectionId, @signalr.GroupName) -> Unit,
  leave~ : async (@signalr.ConnectionId, @signalr.GroupName) -> Unit,
  read_upload~ : async (@signalr.StreamId) -> @signalr.HubValue?,
) -> Backend {
  { send, invoke, join, leave, read_upload, }
}

///|
/// A target with the operation that sends to it.
pub struct ClientProxy {
  priv target : Target
  priv backend : Backend
}

///|
/// The target.
pub fn ClientProxy::target(self : ClientProxy) -> Target {
  self.target
}

///|
/// Call the client method `method_` with `arguments` on each connection of the
/// target, with no result. Two sends of one handler reach a connection in their
/// order.
pub async fn[A] ClientProxy::send(
  self : ClientProxy,
  method_ : @signalr.ClientMethod[A],
  arguments : A,
) -> Unit {
  (self.backend.send)(
    self.target,
    method_.name(),
    method_.arguments().encode(arguments),
  )
}

///|
/// One connection, which can also give a result.
pub struct SingleClient {
  priv id : @signalr.ConnectionId
  priv proxy : ClientProxy
}

///|
/// The target of the connection.
pub fn SingleClient::target(self : SingleClient) -> Target {
  self.proxy.target
}

///|
/// Call the client method `method_` with no result.
pub async fn[A] SingleClient::send(
  self : SingleClient,
  method_ : @signalr.ClientMethod[A],
  arguments : A,
) -> Unit {
  self.proxy.send(method_, arguments)
}

///|
/// Call the client method `call` and wait for its typed result. A client error
/// raises `ClientFailed`; a connection that ends first raises `Disconnected`.
pub async fn[A, R] SingleClient::invoke(
  self : SingleClient,
  call : @signalr.ClientCall[A, R],
  arguments : A,
) -> R {
  let outcome = (self.proxy.backend.invoke)(
    self.id,
    call.name(),
    call.arguments().encode(arguments),
  )
  let value : @signalr.HubValue = match outcome {
    Result(value) => value
    NoResult => Null
    Error(text) => raise ClientFailed(text)
  }
  call.result().decode(value, path=@signalr.Path::named("result"))
}

///|
/// The clients of a hub: each method gives one target.
pub struct Clients {
  priv backend : Backend
}

///|
/// The clients of `backend`. The runtime gives this value for sends from
/// outside a hub method.
pub fn Clients::new(backend : Backend) -> Clients {
  { backend, }
}

///|
/// The clients of any target.
pub fn Clients::target(self : Clients, target : Target) -> ClientProxy {
  { target, backend: self.backend, }
}

///|
/// Every connection.
pub fn Clients::all(self : Clients) -> ClientProxy {
  self.target(All)
}

///|
/// Every connection except `ids`.
pub fn Clients::all_except(
  self : Clients,
  ids : ArrayView[@signalr.ConnectionId],
) -> ClientProxy {
  self.target(AllExcept(ReadOnlyArray::from_array(ids)))
}

///|
/// One connection.
pub fn Clients::client(
  self : Clients,
  id : @signalr.ConnectionId,
) -> SingleClient {
  { id, proxy: self.target(Connections(ReadOnlyArray::from_array([id]))), }
}

///|
/// The connections `ids`.
pub fn Clients::clients(
  self : Clients,
  ids : ArrayView[@signalr.ConnectionId],
) -> ClientProxy {
  self.target(Connections(ReadOnlyArray::from_array(ids)))
}

///|
/// The connections of a group.
pub fn Clients::group(
  self : Clients,
  group : @signalr.GroupName,
) -> ClientProxy {
  self.target(Groups(ReadOnlyArray::from_array([group])))
}

///|
/// The connections of one or more groups. A connection in two of them gets the
/// call one time.
pub fn Clients::groups(
  self : Clients,
  groups : ArrayView[@signalr.GroupName],
) -> ClientProxy {
  self.target(Groups(ReadOnlyArray::from_array(groups)))
}

///|
/// The connections of a group except `ids`.
pub fn Clients::group_except(
  self : Clients,
  group : @signalr.GroupName,
  ids : ArrayView[@signalr.ConnectionId],
) -> ClientProxy {
  self.target(GroupExcept(group, ReadOnlyArray::from_array(ids)))
}

///|
/// The connections of a user.
pub fn Clients::user(self : Clients, user : @signalr.UserId) -> ClientProxy {
  self.target(Users(ReadOnlyArray::from_array([user])))
}

///|
/// The connections of one or more users.
pub fn Clients::users(
  self : Clients,
  users : ArrayView[@signalr.UserId],
) -> ClientProxy {
  self.target(Users(ReadOnlyArray::from_array(users)))
}

///|
/// The clients that a handler can call. It adds the targets that depend on the
/// connection of the current call.
pub struct CallerClients {
  priv caller : @signalr.ConnectionId
  priv clients : Clients
}

///|
/// The targets that do not depend on the current call.
pub fn CallerClients::any(self : CallerClients) -> Clients {
  self.clients
}

///|
/// Every connection.
pub fn CallerClients::all(self : CallerClients) -> ClientProxy {
  self.clients.all()
}

///|
/// The connection of the current call.
pub fn CallerClients::caller(self : CallerClients) -> SingleClient {
  { id: self.caller, proxy: self.clients.target(Caller(self.caller)), }
}

///|
/// Every connection except the one of the current call.
pub fn CallerClients::others(self : CallerClients) -> ClientProxy {
  self.clients.target(Others(self.caller))
}

///|
/// The connections of a group except the one of the current call.
pub fn CallerClients::others_in_group(
  self : CallerClients,
  group : @signalr.GroupName,
) -> ClientProxy {
  self.clients.target(OthersInGroup(group, self.caller))
}

///|
/// One connection.
pub fn CallerClients::client(
  self : CallerClients,
  id : @signalr.ConnectionId,
) -> SingleClient {
  self.clients.client(id)
}

///|
/// The connections of a group.
pub fn CallerClients::group(
  self : CallerClients,
  group : @signalr.GroupName,
) -> ClientProxy {
  self.clients.group(group)
}

///|
/// The connections of a user.
pub fn CallerClients::user(
  self : CallerClients,
  user : @signalr.UserId,
) -> ClientProxy {
  self.clients.user(user)
}

///|
/// The groups of a hub.
pub struct GroupManager {
  priv backend : Backend
}

///|
/// The groups of `backend`.
pub fn GroupManager::new(backend : Backend) -> GroupManager {
  { backend, }
}

///|
/// Add a connection to a group. After the return, a send to the group reaches
/// the connection. A connection that ended is not added.
pub async fn GroupManager::add(
  self : GroupManager,
  id : @signalr.ConnectionId,
  group : @signalr.GroupName,
) -> Unit {
  (self.backend.join)(id, group)
}

///|
/// Remove a connection from a group. When it is not in the group, this has no
/// effect.
pub async fn GroupManager::remove(
  self : GroupManager,
  id : @signalr.ConnectionId,
  group : @signalr.GroupName,
) -> Unit {
  (self.backend.leave)(id, group)
}

///|
/// What a handler knows and can do: the connection of the current call, its
/// identity, the clients and the groups.
pub struct HubContext {
  priv connection_id : @signalr.ConnectionId
  priv identity : @signalr.Identity
  priv uploads : ReadOnlyArray[@signalr.StreamId]
  priv backend : Backend
}

///|
/// A context for a call of the connection `connection_id` with the upload
/// streams `uploads`.
pub fn HubContext::new(
  connection_id : @signalr.ConnectionId,
  identity : @signalr.Identity,
  backend : Backend,
  uploads~ : ReadOnlyArray[@signalr.StreamId] = ReadOnlyArray::from_array([]),
) -> HubContext {
  { connection_id, identity, uploads, backend, }
}

///|
/// The connection of the current call.
pub fn HubContext::connection_id(self : HubContext) -> @signalr.ConnectionId {
  self.connection_id
}

///|
/// Who the connection belongs to.
pub fn HubContext::identity(self : HubContext) -> @signalr.Identity {
  self.identity
}

///|
/// The user ID of the identity, or `None` for an anonymous connection.
pub fn HubContext::user_id(self : HubContext) -> @signalr.UserId? {
  self.identity.user_id()
}

///|
/// The clients of the hub.
pub fn HubContext::clients(self : HubContext) -> CallerClients {
  { caller: self.connection_id, clients: Clients::new(self.backend), }
}

///|
/// The groups of the hub.
pub fn HubContext::groups(self : HubContext) -> GroupManager {
  GroupManager::new(self.backend)
}

///|
/// The upload streams of the current call, in the order of the client.
pub fn HubContext::uploads(
  self : HubContext,
) -> ReadOnlyArray[@signalr.StreamId] {
  self.uploads
}

///|
/// The next item of an upload stream, or `None` at its end. A stream that the
/// client ends with an error raises `HubError` with that text.
pub async fn[T] HubContext::read_upload(
  self : HubContext,
  stream : @signalr.StreamId,
  item : @signalr.Codec[T],
) -> T? {
  match (self.backend.read_upload)(stream) {
    Some(value) => Some(item.decode(value, path=@signalr.Path::named("item")))
    None => None
  }
}