///|
/// The headers of a hub message: string keys, each one time, with string values.
#derive(Eq, Hash, Debug)
pub struct Headers {
  priv entries : ReadOnlyArray[(String, String)]
}

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

///|
pub extend Headers with Hash::{hash, hash_combine}

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

///|
/// No headers.
pub fn Headers::empty() -> Headers {
  { entries: ReadOnlyArray::from_array([]), }
}

///|
/// The headers of `entries`. A key that comes two times raises `DuplicateKey`.
pub fn Headers::new(
  entries : ArrayView[(String, String)],
) -> Headers raise HubValueError {
  for i, entry in entries {
    for j in 0.. String? {
  for entry in self.entries {
    if entry.0 == key {
      return Some(entry.1)
    }
  }
  None
}

///|
/// The headers in their order.
pub fn Headers::iter(self : Headers) -> Iter[(String, String)] {
  self.entries.iter()
}

///|
/// True when there are no headers.
pub fn Headers::is_empty(self : Headers) -> Bool {
  self.entries.is_empty()
}

///|
/// An Invocation (type 1). With no ID it is a non-blocking invocation: the
/// callee sends no reply.
#derive(Eq, Debug)
pub(all) struct Invocation {
  invocation_id : InvocationId?
  target : MethodName
  arguments : ReadOnlyArray[HubValue]
  stream_ids : ReadOnlyArray[StreamId]
  headers : Headers
}

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

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

///|
/// A StreamInvocation (type 4): a call whose results are StreamItem messages.
#derive(Eq, Debug)
pub(all) struct StreamInvocation {
  invocation_id : InvocationId
  target : MethodName
  arguments : ReadOnlyArray[HubValue]
  stream_ids : ReadOnlyArray[StreamId]
  headers : Headers
}

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

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

///|
/// A StreamItem (type 2): one item of a stream. The ID is an invocation ID for
/// a server stream, or a stream ID for an upload stream.
#derive(Eq, Debug)
pub(all) struct StreamItem {
  invocation_id : InvocationId
  item : HubValue
  headers : Headers
}

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

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

///|
/// The outcome of a Completion: no result, a result or an error. A Completion
/// with a result and an error cannot exist.
#derive(Eq, Debug)
pub(all) enum Outcome {
  /// The method has no result, or the stream ended.
  NoResult
  Result(HubValue)
  Error(String)
}

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

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

///|
/// A Completion (type 3): the end of an invocation, a server stream or an
/// upload stream.
#derive(Eq, Debug)
pub(all) struct Completion {
  invocation_id : InvocationId
  outcome : Outcome
  headers : Headers
}

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

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

///|
/// A CancelInvocation (type 5).
#derive(Eq, Debug)
pub(all) struct CancelInvocation {
  invocation_id : InvocationId
  headers : Headers
}

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

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

///|
/// A Close message (type 7). `error` is set only when the connection ends
/// because of an error.
#derive(Eq, Debug)
pub(all) struct Close {
  error : String?
  allow_reconnect : Bool
  headers : Headers
}

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

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

///|
/// A message of the SignalR hub protocol.
#derive(Eq, Debug)
pub(all) enum HubMessage {
  Invocation(Invocation)
  StreamItem(StreamItem)
  Completion(Completion)
  StreamInvocation(StreamInvocation)
  CancelInvocation(CancelInvocation)
  Ping
  Close(Close)
}

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

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

///|
/// The message type number of the protocol, from 1 to 7.
pub fn HubMessage::message_type(self : HubMessage) -> Int32 {
  match self {
    Invocation(_) => 1
    StreamItem(_) => 2
    Completion(_) => 3
    StreamInvocation(_) => 4
    CancelInvocation(_) => 5
    Ping => 6
    Close(_) => 7
  }
}

///|
/// The fields of a JSON object that a reader has not read yet. The reader takes
/// each field that the message type defines; a field that stays is unknown.
priv struct Fields {
  object : Map[String, Json]
  taken : Array[String]
}

///|
fn Fields::take(self : Fields, name : String) -> Json? {
  self.taken.push(name)
  self.object.get(name)
}

///|
fn Fields::require(self : Fields, name : String) -> Json raise ProtocolError {
  guard self.take(name) is Some(value) else { raise MissingField(field=name) }
  value
}

///|
/// Raise `UnknownField` for the first field that the reader did not take.
fn Fields::finish(self : Fields) -> Unit raise ProtocolError {
  for key, _ in self.object {
    guard self.taken.contains(key) else { raise UnknownField(field=key) }
  }
}

///|
fn string_field(json : Json, field : String) -> String raise ProtocolError {
  guard json is String(text) else {
    raise WrongFieldType(field~, expected="a string")
  }
  text
}

///|
fn invocation_id_field(
  json : Json,
  field : String,
) -> InvocationId raise ProtocolError {
  let text = string_field(json, field)
  InvocationId::parse(text) catch {
    error => raise BadIdentifier(field~, error~)
  }
}

///|
fn method_field(json : Json, field : String) -> MethodName raise ProtocolError {
  let text = string_field(json, field)
  MethodName::parse(text) catch {
    error => raise BadIdentifier(field~, error~)
  }
}

///|
fn arguments_field(json : Json) -> ReadOnlyArray[HubValue] raise ProtocolError {
  guard json is Array(items) else {
    raise WrongFieldType(field="arguments", expected="an array")
  }
  let values = []
  for item in items {
    values.push(HubValue::from_json(item))
  }
  ReadOnlyArray::from_array(values)
}

///|
fn stream_ids_field(
  json : Json?,
) -> ReadOnlyArray[StreamId] raise ProtocolError {
  match json {
    None => ReadOnlyArray::from_array([])
    Some(Array(items)) => {
      let ids = []
      for item in items {
        let text = string_field(item, "streamIds")
        ids.push(
          StreamId::parse(text) catch {
            error => raise BadIdentifier(field="streamIds", error~)
          },
        )
      }
      ReadOnlyArray::from_array(ids)
    }
    Some(_) =>
      raise WrongFieldType(field="streamIds", expected="an array of strings")
  }
}

///|
fn headers_field(json : Json?) -> Headers raise ProtocolError {
  match json {
    None => Headers::empty()
    Some(Object(map)) => {
      let entries = []
      for key, value in map {
        guard value is String(text) else {
          raise WrongFieldType(field="headers", expected="an object of strings")
        }
        entries.push((key, text))
      }
      Headers::new(entries) catch {
        _ =>
          raise WrongFieldType(field="headers", expected="an object of strings")
      }
    }
    Some(_) =>
      raise WrongFieldType(field="headers", expected="an object of strings")
  }
}

///|
/// Read one hub message from its JSON text, without the record separator. The
/// reader is strict: a missing required field, a field of the wrong type and a
/// field that the type does not define are errors.
pub fn HubMessage::parse(text : StringView) -> HubMessage raise ProtocolError {
  guard parse_json(text) is Object(object) else { raise NotAnObject }
  let fields : Fields = { object, taken: [], }
  let message_type = match fields.require("type") {
    Number(value, ..) if value.floor() == value &&
      value >= 1.0 &&
      value <= 255.0 => value.to_int()
    Number(value, ..) if value.floor() == value =>
      raise UnsupportedMessageType(message_type=value.to_int())
    _ => raise WrongFieldType(field="type", expected="an integer")
  }
  let message = match message_type {
    1 => {
      let invocation_id = match fields.take("invocationId") {
        None => None
        Some(json) => Some(invocation_id_field(json, "invocationId"))
      }
      Invocation({
        invocation_id,
        target: method_field(fields.require("target"), "target"),
        arguments: arguments_field(fields.require("arguments")),
        stream_ids: stream_ids_field(fields.take("streamIds")),
        headers: headers_field(fields.take("headers")),
      })
    }
    2 =>
      StreamItem({
        invocation_id: invocation_id_field(
          fields.require("invocationId"),
          "invocationId",
        ),
        item: HubValue::from_json(fields.require("item")),
        headers: headers_field(fields.take("headers")),
      })
    3 => {
      let invocation_id = invocation_id_field(
        fields.require("invocationId"),
        "invocationId",
      )
      let result = fields.take("result")
      let error = fields.take("error")
      let outcome = match (result, error) {
        (Some(_), Some(_)) => raise ResultAndError(invocation_id~)
        (Some(value), None) => Result(HubValue::from_json(value))
        (None, Some(text)) => Error(string_field(text, "error"))
        (None, None) => NoResult
      }
      Completion({
        invocation_id,
        outcome,
        headers: headers_field(fields.take("headers")),
      })
    }
    4 =>
      StreamInvocation({
        invocation_id: invocation_id_field(
          fields.require("invocationId"),
          "invocationId",
        ),
        target: method_field(fields.require("target"), "target"),
        arguments: arguments_field(fields.require("arguments")),
        stream_ids: stream_ids_field(fields.take("streamIds")),
        headers: headers_field(fields.take("headers")),
      })
    5 =>
      CancelInvocation({
        invocation_id: invocation_id_field(
          fields.require("invocationId"),
          "invocationId",
        ),
        headers: headers_field(fields.take("headers")),
      })
    6 => Ping
    7 => {
      let error = match fields.take("error") {
        None | Some(Null) => None
        Some(json) => Some(string_field(json, "error"))
      }
      let allow_reconnect = match fields.take("allowReconnect") {
        None => false
        Some(True) => true
        Some(False) => false
        Some(_) =>
          raise WrongFieldType(field="allowReconnect", expected="a boolean")
      }
      Close({
        error,
        allow_reconnect,
        headers: headers_field(fields.take("headers")),
      })
    }
    other => raise UnsupportedMessageType(message_type=other)
  }
  fields.finish()
  message
}

///|
fn headers_json(headers : Headers, object : Map[String, Json]) -> Unit {
  if !headers.is_empty() {
    let map : Map[String, Json] = Map([])
    for entry in headers.iter() {
      map[entry.0] = Json::string(entry.1)
    }
    object["headers"] = Json::object(map)
  }
}

///|
fn values_json(values : ReadOnlyArray[HubValue]) -> Json {
  Json::array(values.iter().map(value => value.to_json()).collect())
}

///|
fn stream_ids_json(
  ids : ReadOnlyArray[StreamId],
  object : Map[String, Json],
) -> Unit {
  if !ids.is_empty() {
    object["streamIds"] = Json::array(
      ids.iter().map(id => Json::string(id.to_string())).collect(),
    )
  }
}

///|
/// The JSON text of the message, with no record separator. `type` is the first
/// property, as the .NET writer gives it.
pub fn HubMessage::to_json_text(self : HubMessage) -> String {
  let object : Map[String, Json] = Map([])
  object["type"] = Json::number(self.message_type().to_double())
  match self {
    Invocation(message) => {
      if message.invocation_id is Some(id) {
        object["invocationId"] = Json::string(id.to_string())
      }
      object["target"] = Json::string(message.target.to_string())
      object["arguments"] = values_json(message.arguments)
      stream_ids_json(message.stream_ids, object)
      headers_json(message.headers, object)
    }
    StreamItem(message) => {
      object["invocationId"] = Json::string(message.invocation_id.to_string())
      object["item"] = message.item.to_json()
      headers_json(message.headers, object)
    }
    Completion(message) => {
      object["invocationId"] = Json::string(message.invocation_id.to_string())
      match message.outcome {
        NoResult => ()
        Result(value) => object["result"] = value.to_json()
        Error(text) => object["error"] = Json::string(text)
      }
      headers_json(message.headers, object)
    }
    StreamInvocation(message) => {
      object["invocationId"] = Json::string(message.invocation_id.to_string())
      object["target"] = Json::string(message.target.to_string())
      object["arguments"] = values_json(message.arguments)
      stream_ids_json(message.stream_ids, object)
      headers_json(message.headers, object)
    }
    CancelInvocation(message) => {
      object["invocationId"] = Json::string(message.invocation_id.to_string())
      headers_json(message.headers, object)
    }
    Ping => ()
    Close(message) => {
      if message.error is Some(text) {
        object["error"] = Json::string(text)
      }
      if message.allow_reconnect {
        object["allowReconnect"] = Json::boolean(true)
      }
      headers_json(message.headers, object)
    }
  }
  Json::object(object).stringify()
}

///|
/// The framed text of the message: its JSON text and the record separator.
pub fn HubMessage::to_frame(self : HubMessage) -> String {
  frame(self.to_json_text())
}