///|
/// A hub method: the method that a client calls on the hub. It has a name,
/// the codecs of its arguments and the codec of its result, or of its stream
/// items for a streaming method.
pub struct HubMethod[A, R] {
  priv name : MethodName
  priv kind : CallKind
  priv arguments : Arguments[A]
  priv result : Codec[R]
}

///|
/// A hub method with one result. Use `unit()` for a method with no result.
pub fn[A, R] HubMethod::call(
  name : MethodName,
  arguments : Arguments[A],
  result : Codec[R],
) -> HubMethod[A, R] {
  { name, kind: Single, arguments, result, }
}

///|
/// A streaming hub method: a client starts it with a StreamInvocation, and it
/// sends items of the type `R`.
pub fn[A, R] HubMethod::stream(
  name : MethodName,
  arguments : Arguments[A],
  item : Codec[R],
) -> HubMethod[A, R] {
  { name, kind: Stream, arguments, result: item, }
}

///|
/// The method name.
pub fn[A, R] HubMethod::name(self : HubMethod[A, R]) -> MethodName {
  self.name
}

///|
/// `Single` for a method with one result, `Stream` for a streaming method.
pub fn[A, R] HubMethod::kind(self : HubMethod[A, R]) -> CallKind {
  self.kind
}

///|
/// The codecs of the arguments.
pub fn[A, R] HubMethod::arguments(self : HubMethod[A, R]) -> Arguments[A] {
  self.arguments
}

///|
/// The codec of the result, or of the stream items.
pub fn[A, R] HubMethod::result(self : HubMethod[A, R]) -> Codec[R] {
  self.result
}

///|
/// A client method: the method that the hub calls on a client.
pub struct ClientMethod[A] {
  priv name : MethodName
  priv arguments : Arguments[A]
}

///|
/// A client method with no result.
pub fn[A] ClientMethod::new(
  name : MethodName,
  arguments : Arguments[A],
) -> ClientMethod[A] {
  { name, arguments, }
}

///|
/// The method name.
pub fn[A] ClientMethod::name(self : ClientMethod[A]) -> MethodName {
  self.name
}

///|
/// The codecs of the arguments.
pub fn[A] ClientMethod::arguments(self : ClientMethod[A]) -> Arguments[A] {
  self.arguments
}

///|
/// A client method with a result: the hub calls it on one client and waits for
/// the result.
pub struct ClientCall[A, R] {
  priv name : MethodName
  priv arguments : Arguments[A]
  priv result : Codec[R]
}

///|
/// A client method with a result.
pub fn[A, R] ClientCall::new(
  name : MethodName,
  arguments : Arguments[A],
  result : Codec[R],
) -> ClientCall[A, R] {
  { name, arguments, result, }
}

///|
/// The method name.
pub fn[A, R] ClientCall::name(self : ClientCall[A, R]) -> MethodName {
  self.name
}

///|
/// The codecs of the arguments.
pub fn[A, R] ClientCall::arguments(self : ClientCall[A, R]) -> Arguments[A] {
  self.arguments
}

///|
/// The codec of the result.
pub fn[A, R] ClientCall::result(self : ClientCall[A, R]) -> Codec[R] {
  self.result
}

///|
/// A fault in a hub contract.
#derive(Eq, Debug)
pub suberror ContractError {
  /// The contract already has a hub method with this name.
  DuplicateHubMethod(MethodName)
  /// The contract already has a client method with this name.
  DuplicateClientMethod(MethodName)
}

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

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

///|
/// Text for people that describes the fault.
pub fn ContractError::message(self : ContractError) -> String {
  match self {
    DuplicateHubMethod(name) =>
      "The contract already has the hub method '\{name}'."
    DuplicateClientMethod(name) =>
      "The contract already has the client method '\{name}'."
  }
}

///|
/// The name and the kind of a hub method in a contract.
#derive(Eq, Debug)
pub(all) struct MethodInfo {
  name : MethodName
  kind : CallKind
  parameters : Int32
}

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

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

///|
/// A hub contract: the hub name, the hub methods and the client methods (design
/// CON-1). Method names are unique in each direction and case-sensitive. The
/// value is immutable: each builder call gives a new contract.
pub struct HubContract {
  priv name : HubName
  priv hub_methods : ReadOnlyArray[MethodInfo]
  priv client_methods : ReadOnlyArray[MethodInfo]
}

///|
/// A contract with no methods.
pub fn HubContract::new(name : HubName) -> HubContract {
  {
    name,
    hub_methods: ReadOnlyArray::from_array([]),
    client_methods: ReadOnlyArray::from_array([]),
  }
}

///|
/// The hub name.
pub fn HubContract::name(self : HubContract) -> HubName {
  self.name
}

///|
fn added(
  methods : ReadOnlyArray[MethodInfo],
  info : MethodInfo,
) -> ReadOnlyArray[MethodInfo] {
  let all = methods.iter().collect()
  all.push(info)
  ReadOnlyArray::from_array(all)
}

///|
/// Add a hub method. A name that the contract has for a hub method raises
/// `DuplicateHubMethod`.
pub fn[A, R] HubContract::server(
  self : HubContract,
  method_ : HubMethod[A, R],
) -> HubContract raise ContractError {
  guard !self.hub_methods.iter().any(info => info.name == method_.name) else {
    raise DuplicateHubMethod(method_.name)
  }
  let info = {
    name: method_.name,
    kind: method_.kind,
    parameters: method_.arguments.count,
  }
  { ..self, hub_methods: added(self.hub_methods, info), }
}

///|
/// Add a client method. A name that the contract has for a client method
/// raises `DuplicateClientMethod`.
pub fn[A] HubContract::client(
  self : HubContract,
  method_ : ClientMethod[A],
) -> HubContract raise ContractError {
  guard !self.client_methods.iter().any(info => info.name == method_.name) else {
    raise DuplicateClientMethod(method_.name)
  }
  let info = {
    name: method_.name,
    kind: Single,
    parameters: method_.arguments.count,
  }
  { ..self, client_methods: added(self.client_methods, info), }
}

///|
/// Add a client method with a result. Its name is in the same set as the names
/// of the client methods with no result.
pub fn[A, R] HubContract::client_call(
  self : HubContract,
  call : ClientCall[A, R],
) -> HubContract raise ContractError {
  self.client(ClientMethod::new(call.name, call.arguments))
}

///|
/// The hub methods, in the order in which they were added.
pub fn HubContract::hub_methods(self : HubContract) -> Array[MethodInfo] {
  self.hub_methods.iter().collect()
}

///|
/// The client methods, in the order in which they were added.
pub fn HubContract::client_methods(self : HubContract) -> Array[MethodInfo] {
  self.client_methods.iter().collect()
}

///|
/// The hub method of a call, or the error text for the Completion when the
/// call does not fit the contract: an unknown method, or a call of the wrong
/// kind. The texts for the wrong kind are the texts of ASP.NET Core.
pub fn HubContract::check_call(
  self : HubContract,
  call : Call,
) -> Result[MethodInfo, String] {
  guard self.hub_methods.iter().find_first(info => info.name == call.target)
    is Some(info) else {
    return Err("Unknown hub method '\{call.target}'")
  }
  match (info.kind, call.kind) {
    (Stream, Single) =>
      Err(
        "The client attempted to invoke the streaming '\{info.name}' method with a non-streaming invocation.",
      )
    (Single, Stream) =>
      Err(
        "The client attempted to invoke the non-streaming '\{info.name}' method with a streaming invocation.",
      )
    _ => Ok(info)
  }
}