///|
/// A transport of the SignalR connection protocol.
#derive(Eq, Debug)
pub(all) enum TransportKind {
  WebSockets
  ServerSentEvents
  LongPolling
  /// A transport that this library does not know.
  Other(String)
}

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

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

///|
/// The name of the transport in negotiate payloads.
pub fn TransportKind::name(self : TransportKind) -> String {
  match self {
    WebSockets => "WebSockets"
    ServerSentEvents => "ServerSentEvents"
    LongPolling => "LongPolling"
    Other(name) => name
  }
}

///|
fn TransportKind::of_name(name : String) -> TransportKind {
  match name {
    "WebSockets" => WebSockets
    "ServerSentEvents" => ServerSentEvents
    "LongPolling" => LongPolling
    other => Other(other)
  }
}

///|
/// A transfer format of a transport.
#derive(Eq, Debug)
pub(all) enum TransferFormat {
  Text
  Binary
  /// A format that this library does not know.
  Other(String)
}

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

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

///|
/// The name of the format in negotiate payloads.
pub fn TransferFormat::name(self : TransferFormat) -> String {
  match self {
    Text => "Text"
    Binary => "Binary"
    Other(name) => name
  }
}

///|
fn TransferFormat::of_name(name : String) -> TransferFormat {
  match name {
    "Text" => Text
    "Binary" => Binary
    other => Other(other)
  }
}

///|
/// A transport that a server offers, with its transfer formats.
#derive(Eq, Debug)
pub(all) struct AvailableTransport {
  transport : TransportKind
  formats : ReadOnlyArray[TransferFormat]
}

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

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

///|
/// The WebSockets transport with the formats `Text` and `Binary`, which a
/// Moon-Lander server offers.
pub fn AvailableTransport::websockets() -> AvailableTransport {
  { transport: WebSockets, formats: ReadOnlyArray::from_array([Text, Binary]), }
}

///|
/// A version of the negotiate request that the protocol defines.
#derive(Eq, Debug)
pub(all) enum NegotiateVersion {
  /// The connection ID also opens the transport.
  Version0
  /// A private connection token opens the transport.
  Version1
}

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

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

///|
/// The connection token that a negotiate version gives. Version 0 has no token; a
/// client then connects with the connection ID. The token of version 1 is
/// separate from the connection ID.
#derive(Eq, Debug)
pub(all) enum NegotiatedToken {
  /// Negotiate version 0: no token.
  Version0
  /// Negotiate version 1, with the private token.
  Version1(ConnectionToken)
}

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

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

///|
/// A negotiated connection. The debug representation shows the connection ID
/// and `[REDACTED]` for the token.
#derive(Eq, Debug)
pub(all) struct NegotiatedConnection {
  connection_id : ConnectionId
  token : NegotiatedToken
  transports : ReadOnlyArray[AvailableTransport]
}

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

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

///|
/// The negotiate version of the connection.
pub fn NegotiatedConnection::negotiate_version(
  self : NegotiatedConnection,
) -> NegotiateVersion {
  match self.token {
    Version0 => Version0
    Version1(_) => Version1
  }
}

///|
/// The text of the `id` query value of the transport request: the token for
/// version 1 and later, the connection ID for version 0.
pub fn NegotiatedConnection::transport_id(
  self : NegotiatedConnection,
) -> String {
  match self.token {
    Version0 => self.connection_id.to_string()
    Version1(token) => token.expose()
  }
}

///|
/// A negotiate response: a connection, a redirect to another server, or a
/// refusal with an error text.
#derive(Eq, Debug)
pub(all) enum NegotiateResponse {
  Connection(NegotiatedConnection)
  Redirect(url~ : String, access_token~ : AccessToken?)
  Refused(String)
}

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

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

///|
fn required_string(
  object : Map[String, Json],
  field : String,
) -> String raise ProtocolError {
  guard object.get(field) is Some(json) else { raise MissingField(field~) }
  string_field(json, field)
}

///|
fn transports_field(
  object : Map[String, Json],
) -> ReadOnlyArray[AvailableTransport] raise ProtocolError {
  let expected = "an array of transports"
  guard object.get("availableTransports") is Some(json) else {
    return ReadOnlyArray::from_array([])
  }
  guard json is Array(items) else {
    raise WrongFieldType(field="availableTransports", expected~)
  }
  let transports = []
  for item in items {
    guard item is Object(entry) && entry.get("transport") is Some(String(name)) else {
      raise WrongFieldType(field="availableTransports", expected~)
    }
    let formats = match entry.get("transferFormats") {
      None => []
      Some(Array(names)) => {
        let formats = []
        for format in names {
          guard format is String(text) else {
            raise WrongFieldType(
              field="transferFormats",
              expected="an array of strings",
            )
          }
          formats.push(TransferFormat::of_name(text))
        }
        formats
      }
      Some(_) =>
        raise WrongFieldType(
          field="transferFormats",
          expected="an array of strings",
        )
    }
    transports.push({
      transport: TransportKind::of_name(name),
      formats: ReadOnlyArray::from_array(formats),
    })
  }
  ReadOnlyArray::from_array(transports)
}

///|
/// Read a negotiate response from its JSON text. Properties that the reader
/// does not know are ignored, so that a newer server does not break it.
pub fn NegotiateResponse::parse(
  text : StringView,
) -> NegotiateResponse raise ProtocolError {
  guard parse_json(text) is Object(object) else { raise NotAnObject }
  if object.get("error") is Some(error) && !(error is Null) {
    return Refused(string_field(error, "error"))
  }
  if object.get("url") is Some(url) && !(url is Null) {
    let access_token = match object.get("accessToken") {
      None | Some(Null) => None
      Some(json) => {
        let token = string_field(json, "accessToken")
        Some(
          AccessToken::parse(token) catch {
            error => raise BadIdentifier(field="accessToken", error~)
          },
        )
      }
    }
    return Redirect(url=string_field(url, "url"), access_token~)
  }
  let version = match object.get("negotiateVersion") {
    None => 0
    Some(Number(number, ..)) if number.floor() == number &&
      number >= 0.0 &&
      number <= 2147483647.0 => number.to_int()
    Some(_) =>
      raise WrongFieldType(field="negotiateVersion", expected="an integer")
  }
  let id_text = required_string(object, "connectionId")
  let connection_id = ConnectionId::parse(id_text) catch {
    error => raise BadIdentifier(field="connectionId", error~)
  }
  let token : NegotiatedToken = if version == 0 {
    Version0
  } else {
    let token_text = required_string(object, "connectionToken")
    let token = ConnectionToken::parse(token_text) catch {
      error => raise BadIdentifier(field="connectionToken", error~)
    }
    Version1(token)
  }
  Connection({ connection_id, token, transports: transports_field(object), })
}

///|
/// The JSON text of the response, as a server writes it.
pub fn NegotiateResponse::to_json_text(self : NegotiateResponse) -> String {
  let object : Map[String, Json] = Map([])
  match self {
    Connection(connection) => {
      object["negotiateVersion"] = Json::number(
        if connection.token is Version0 {
          0
        } else {
          1
        },
      )
      object["connectionId"] = Json::string(
        connection.connection_id.to_string(),
      )
      if connection.token is Version1(token) {
        object["connectionToken"] = Json::string(token.expose())
      }
      object["availableTransports"] = Json::array(
        connection.transports
        .iter()
        .map(transport => {
          let entry : Map[String, Json] = Map([])
          entry["transport"] = Json::string(transport.transport.name())
          entry["transferFormats"] = Json::array(
            transport.formats
            .iter()
            .map(format => Json::string(format.name()))
            .collect(),
          )
          Json::object(entry)
        })
        .collect(),
      )
    }
    Redirect(url~, access_token~) => {
      object["url"] = Json::string(url)
      if access_token is Some(token) {
        object["accessToken"] = Json::string(token.expose())
      }
    }
    Refused(error) => object["error"] = Json::string(error)
  }
  Json::object(object).stringify()
}