///|
/// A fault in the binding of a hub.
#derive(Eq, Debug)
pub suberror BindError {
  /// These hub methods of the contract have no handler.
  MissingHandlers(Array[@signalr.MethodName])
  /// The contract has no hub method with this name and this kind.
  NotInContract(@signalr.MethodName)
  /// The hub method already has a handler.
  DuplicateHandler(@signalr.MethodName)
}

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

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

///|
/// Text for people that describes the fault.
pub fn BindError::message(self : BindError) -> String {
  match self {
    MissingHandlers(names) =>
      "These hub methods have no handler: \{names.map(name => name.to_string()).join(", ")}"
    NotInContract(name) =>
      "The contract has no hub method '\{name}' of this kind."
    DuplicateHandler(name) => "The hub method '\{name}' already has a handler."
  }
}

///|
priv enum Handler {
  Single(async (HubContext, @signalr.Call) -> @signalr.HubValue?)
  Stream(
    async (HubContext, @signalr.Call, async (@signalr.HubValue) -> Unit) -> Unit,
  )
}

///|
priv struct Binding {
  policy : (@signalr.Identity) -> Bool
  handler : Handler
}

///|
/// A hub in construction: a contract and the handlers that are bound so far.
/// Each call gives a new value.
pub struct HubBuilder {
  priv contract : @signalr.HubContract
  priv bindings : @hashmap.HashMap[@signalr.MethodName, Binding]
  priv connected : async (HubContext) -> Unit
  priv disconnected : async (HubContext, @signalr.DisconnectCause) -> Unit
}

///|
/// A hub: a contract with one handler for each hub method (design CON-1).
pub struct Hub {
  priv contract : @signalr.HubContract
  priv bindings : @hashmap.HashMap[@signalr.MethodName, Binding]
  priv connected : async (HubContext) -> Unit
  priv disconnected : async (HubContext, @signalr.DisconnectCause) -> Unit
}

///|
/// Start to bind the handlers of `contract`.
pub fn bind(contract : @signalr.HubContract) -> HubBuilder {
  {
    contract,
    bindings: @hashmap.HashMap::empty(),
    connected: _ => (),
    disconnected: (_, _) => (),
  }
}

///|
/// The arguments of a call. An argument that does not decode raises `HubError`
/// with the method and the failed argument, because the caller can correct it.
fn[A] decode_arguments(
  arguments : @signalr.Arguments[A],
  call : @signalr.Call,
) -> A raise @signalr.HubError {
  arguments.decode(call.arguments) catch {
    error => {
      let reason = match error {
        // The text of the error of a domain type is for the program.
        Rejected(path~, ..) => "\{path}: the value is not valid"
        _ => error.message()
      }
      raise HubError("Failed to invoke '\{call.target}': \{reason}")
    }
  }
}

///|
fn HubBuilder::add(
  self : HubBuilder,
  name : @signalr.MethodName,
  kind : @signalr.CallKind,
  binding : Binding,
) -> HubBuilder raise BindError {
  guard self.contract
    .hub_methods()
    .iter()
    .any(info => info.name == name && info.kind == kind) else {
    raise NotInContract(name)
  }
  guard !self.bindings.contains(name) else { raise DuplicateHandler(name) }
  { ..self, bindings: self.bindings.insert(name, binding), }
}

///|
/// Bind the handler of a hub method with one result. The handler gets the typed
/// arguments. `policy` gets the identity of the caller; when it gives false, the
/// handler does not run and the caller gets an error.
pub fn[A, R] HubBuilder::on(
  self : HubBuilder,
  method_ : @signalr.HubMethod[A, R],
  handler : async (HubContext, A) -> R,
  policy~ : (@signalr.Identity) -> Bool = _ => true,
) -> HubBuilder raise BindError {
  self.add(method_.name(), Single, {
    policy,
    handler: Single((context, call) => {
      let arguments = decode_arguments(method_.arguments(), call)
      let value = method_.result().encode(handler(context, arguments))
      if method_.result().has_no_result() {
        None
      } else {
        Some(value)
      }
    }),
  })
}

///|
/// Bind the handler of a streaming hub method. The handler sends each item with
/// its third argument, which waits when the client reads slowly. When the client
/// cancels the stream, the task of the handler is cancelled.
pub fn[A, R] HubBuilder::on_stream(
  self : HubBuilder,
  method_ : @signalr.HubMethod[A, R],
  handler : async (HubContext, A, async (R) -> Unit) -> Unit,
  policy~ : (@signalr.Identity) -> Bool = _ => true,
) -> HubBuilder raise BindError {
  self.add(method_.name(), Stream, {
    policy,
    handler: Stream((context, call, emit) => {
      let arguments = decode_arguments(method_.arguments(), call)
      handler(context, arguments, item => emit(method_.result().encode(item)))
    }),
  })
}

///|
/// The handler that runs after the handshake and before the first hub method of
/// a connection. An error refuses the connection.
pub fn HubBuilder::on_connected(
  self : HubBuilder,
  handler : async (HubContext) -> Unit,
) -> HubBuilder {
  { ..self, connected: handler, }
}

///|
/// The handler that runs one time after a connection ended, with the cause.
pub fn HubBuilder::on_disconnected(
  self : HubBuilder,
  handler : async (HubContext, @signalr.DisconnectCause) -> Unit,
) -> HubBuilder {
  { ..self, disconnected: handler, }
}

///|
/// The hub. A hub method of the contract with no handler raises
/// `MissingHandlers` with each such name.
pub fn HubBuilder::build(self : HubBuilder) -> Hub raise BindError {
  let missing = self.contract
    .hub_methods()
    .filter(info => !self.bindings.contains(info.name))
    .map(info => info.name)
  guard missing.is_empty() else { raise MissingHandlers(missing) }
  {
    contract: self.contract,
    bindings: self.bindings,
    connected: self.connected,
    disconnected: self.disconnected,
  }
}

///|
/// The contract of the hub.
pub fn Hub::contract(self : Hub) -> @signalr.HubContract {
  self.contract
}

///|
/// The handler of a call that the contract and the policy permit.
fn Hub::handler(
  self : Hub,
  context : HubContext,
  call : @signalr.Call,
) -> Handler raise @signalr.HubError {
  if self.contract.check_call(call) is Err(text) {
    raise HubError(text)
  }
  guard self.bindings.get(call.target) is Some(binding) else {
    raise HubError("Unknown hub method '\{call.target}'")
  }
  guard (binding.policy)(context.identity) else {
    raise HubError(
      "Failed to invoke '\{call.target}' because the call is not authorized",
    )
  }
  binding.handler
}

///|
/// Run the handler of a call with one result. Gives the result, or `None` for a
/// method with no result.
pub async fn Hub::invoke(
  self : Hub,
  context : HubContext,
  call : @signalr.Call,
) -> @signalr.HubValue? {
  match self.handler(context, call) {
    Single(run) => run(context, call)
    Stream(_) => None
  }
}

///|
/// Run the handler of a streaming call, which sends each item with `emit`.
pub async fn Hub::stream(
  self : Hub,
  context : HubContext,
  call : @signalr.Call,
  emit : async (@signalr.HubValue) -> Unit,
) -> Unit {
  if self.handler(context, call) is Stream(run) {
    run(context, call, emit)
  }
}

///|
/// Run the connect handler.
pub async fn Hub::connected(self : Hub, context : HubContext) -> Unit {
  (self.connected)(context)
}

///|
/// Run the disconnect handler.
pub async fn Hub::disconnected(
  self : Hub,
  context : HubContext,
  cause : @signalr.DisconnectCause,
) -> Unit {
  (self.disconnected)(context, cause)
}