///|
/// The handshake request that a client sends first: the protocol name and its
/// version. Handshake messages are JSON for every protocol.
#derive(Eq, Debug)
pub(all) struct HandshakeRequest {
  protocol : String
  version : Int32
}

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

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

///|
/// The request for the JSON protocol, version 1.
pub fn HandshakeRequest::json() -> HandshakeRequest {
  { protocol: "json", version: 1, }
}

///|
/// Read a handshake request from its JSON text, without the record separator.
/// Properties that the reader does not know are ignored.
pub fn HandshakeRequest::parse(
  text : StringView,
) -> HandshakeRequest raise ProtocolError {
  guard parse_json(text) is Object(object) else { raise NotAnObject }
  guard object.get("protocol") is Some(protocol) else {
    raise MissingField(field="protocol")
  }
  guard object.get("version") is Some(version) else {
    raise MissingField(field="version")
  }
  guard version is Number(number, ..) &&
    number.floor() == number &&
    number >= 0.0 &&
    number <= 2147483647.0 else {
    raise WrongFieldType(field="version", expected="an integer")
  }
  { protocol: string_field(protocol, "protocol"), version: number.to_int(), }
}

///|
/// The framed text of the request.
pub fn HandshakeRequest::to_frame(self : HandshakeRequest) -> String {
  let object : Map[String, Json] = Map([])
  object["protocol"] = Json::string(self.protocol)
  object["version"] = Json::number(self.version.to_double())
  frame(Json::object(object).stringify())
}

///|
/// The handshake response of a server: accepted (`{}`) or refused with an
/// error text.
#derive(Eq, Debug)
pub(all) enum HandshakeResponse {
  Accepted
  Refused(String)
}

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

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

///|
/// The response of a server that supports only the JSON protocol, version 1, to
/// `request`. The error texts are the texts of ASP.NET Core.
pub fn HandshakeResponse::for_request(
  request : HandshakeRequest,
) -> HandshakeResponse {
  if request.protocol != "json" {
    Refused("The protocol '\{request.protocol}' is not supported.")
  } else if request.version != 1 {
    Refused(
      "The server does not support version \{request.version} of the '\{request.protocol}' protocol.",
    )
  } else {
    Accepted
  }
}

///|
/// Read a handshake response from its JSON text, without the record separator.
/// Properties that the reader does not know are ignored.
pub fn HandshakeResponse::parse(
  text : StringView,
) -> HandshakeResponse raise ProtocolError {
  guard parse_json(text) is Object(object) else { raise NotAnObject }
  match object.get("error") {
    None | Some(Null) => Accepted
    Some(error) => Refused(string_field(error, "error"))
  }
}

///|
/// The framed text of the response.
pub fn HandshakeResponse::to_frame(self : HandshakeResponse) -> String {
  match self {
    Accepted => frame("{}")
    Refused(error) => {
      let object : Map[String, Json] = Map([])
      object["error"] = Json::string(error)
      frame(Json::object(object).stringify())
    }
  }
}