///|
/// The kind of a SignalR identifier or name. A parse error names it, so a caller
/// knows which value failed.
#derive(Eq, Debug)
pub(all) enum IdentifierKind {
  HubName
  MethodName
  InvocationId
  StreamId
  ConnectionId
  ConnectionToken
  UserId
  GroupName
  EndpointPath
  AccessToken
}

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

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

///|
/// The rule of an identifier that a text breaks.
#derive(Eq, Debug)
pub(all) enum IdentifierRule {
  /// The text is empty.
  Empty
  /// The text has more than `limit` characters. `length` is its number of
  /// characters.
  TooLong(limit~ : Int32, length~ : Int32)
  /// The first character is not allowed at the start.
  FirstCharNotAllowed(Char)
  /// The text holds a character that the identifier does not allow.
  CharNotAllowed(Char)
  /// An endpoint path does not start with `/`.
  NoLeadingSlash
  /// An endpoint path has an empty segment, for example `/`, `//chat` or `/chat/`.
  EmptySegment
}

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

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

///|
/// A text that is not a valid identifier. Callers can match the cases, but only
/// the smart constructors make them. The text of a connection token is never
/// kept in the error.
#derive(Eq, Debug)
pub suberror IdentifierError {
  /// The text `text` breaks the rule `rule` of the identifier kind `kind`.
  InvalidIdentifier(
    kind~ : IdentifierKind,
    text~ : String,
    rule~ : IdentifierRule,
  )
}

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

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

///|
/// Text for people that describes the fault.
pub fn IdentifierError::message(self : IdentifierError) -> String {
  let InvalidIdentifier(kind~, text~, rule~) = self
  let reason = match rule {
    Empty => "the text is empty"
    TooLong(limit~, length~) =>
      "the text has \{length} characters; the limit is \{limit}"
    FirstCharNotAllowed(char) =>
      "the first character \{char.to_string().escape()} is not allowed"
    CharNotAllowed(char) =>
      "the character \{char.to_string().escape()} is not allowed"
    NoLeadingSlash => "the path must start with '/'"
    EmptySegment => "the path has an empty segment"
  }
  "Invalid \{kind_label(kind)} \{text.escape()}: \{reason}"
}

///|
fn kind_label(kind : IdentifierKind) -> String {
  match kind {
    HubName => "hub name"
    MethodName => "method name"
    InvocationId => "invocation ID"
    StreamId => "stream ID"
    ConnectionId => "connection ID"
    ConnectionToken => "connection token"
    UserId => "user ID"
    GroupName => "group name"
    EndpointPath => "endpoint path"
    AccessToken => "access token"
  }
}

///|
/// The text that an error about a connection token shows in place of the token.
let redacted : String = "[REDACTED]"

///|
/// The number of characters (Unicode scalar values) in `text`.
fn char_count(text : String) -> Int32 {
  let mut count = 0
  for _ in text {
    count += 1
  }
  count
}

///|
fn is_control(char : Char) -> Bool {
  let code = char.to_int()
  code < 0x20 || (code >= 0x7F && code <= 0x9F)
}

///|
fn is_ascii_letter(char : Char) -> Bool {
  (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z')
}

///|
fn is_ascii_digit(char : Char) -> Bool {
  char >= '0' && char <= '9'
}

///|
/// Check the common rules of a text identifier: not empty, at most `limit`
/// characters, and no control characters. When `no_space` is true, a space
/// character is also not allowed. `shown` is the text that an error holds.
fn check_text(
  kind : IdentifierKind,
  text : String,
  limit : Int32,
  no_space~ : Bool = false,
  shown? : String,
) -> Unit raise IdentifierError {
  let shown = shown.unwrap_or(text)
  guard !text.is_empty() else {
    raise InvalidIdentifier(kind~, text=shown, rule=Empty)
  }
  let length = char_count(text)
  guard length <= limit else {
    raise InvalidIdentifier(kind~, text=shown, rule=TooLong(limit~, length~))
  }
  for char in text {
    guard !is_control(char) && !(no_space && char.is_whitespace()) else {
      raise InvalidIdentifier(kind~, text=shown, rule=CharNotAllowed(char))
    }
  }
}

///|
/// The limit of the length of the IDs that a peer chooses: invocation IDs and
/// stream IDs (design PROTO-2).
pub let id_length_limit : Int32 = 128

///|
/// The limit of the length of names and of the IDs that a server gives.
pub let name_length_limit : Int32 = 256

///|
/// The name of a hub, for example `chat`. It starts with an ASCII letter and
/// holds only ASCII letters, digits, `-` and `_`, with at most 128 characters.
#derive(Eq, Hash, Debug)
pub struct HubName {
  priv text : String
}

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

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

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

///|
/// Parse a hub name.
pub fn HubName::parse(text : String) -> HubName raise IdentifierError {
  check_text(HubName, text, id_length_limit)
  guard text.iter().head() is Some(first) && is_ascii_letter(first) else {
    raise InvalidIdentifier(
      kind=HubName,
      text~,
      rule=FirstCharNotAllowed(text.iter().head().unwrap_or(' ')),
    )
  }
  for char in text {
    guard is_ascii_letter(char) ||
      is_ascii_digit(char) ||
      char == '-' ||
      char == '_' else {
      raise InvalidIdentifier(kind=HubName, text~, rule=CharNotAllowed(char))
    }
  }
  { text, }
}

///|
pub impl Show for HubName with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend HubName with Show::{output, to_string}

///|
/// The name of a hub method or a client method, for example `sendMessage`. It
/// has 1 to 128 characters, and no control or space characters.
#derive(Eq, Hash, Debug)
pub struct MethodName {
  priv text : String
}

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

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

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

///|
/// Parse a method name.
pub fn MethodName::parse(text : String) -> MethodName raise IdentifierError {
  check_text(MethodName, text, id_length_limit, no_space=true)
  { text, }
}

///|
pub impl Show for MethodName with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend MethodName with Show::{output, to_string}

///|
/// The ID of an invocation that the caller chooses for each connection. It has 1
/// to 128 characters and no control characters (signalr-protocol, "Invocation
/// identifiers").
#derive(Eq, Hash, Debug)
pub struct InvocationId {
  priv text : String
}

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

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

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

///|
/// Parse an invocation ID.
pub fn InvocationId::parse(text : String) -> InvocationId raise IdentifierError {
  check_text(InvocationId, text, id_length_limit)
  { text, }
}

///|
/// The invocation ID for a counter value, as the .NET and JavaScript clients
/// write it: the decimal text of `value`.
pub fn InvocationId::from_counter(value : UInt64) -> InvocationId {
  { text: value.to_string(), }
}

///|
pub impl Show for InvocationId with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend InvocationId with Show::{output, to_string}

///|
/// The ID of an upload stream. It has the rules of an invocation ID.
#derive(Eq, Hash, Debug)
pub struct StreamId {
  priv text : String
}

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

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

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

///|
/// Parse a stream ID.
pub fn StreamId::parse(text : String) -> StreamId raise IdentifierError {
  check_text(StreamId, text, id_length_limit)
  { text, }
}

///|
/// The stream ID for a counter value: the decimal text of `value`.
pub fn StreamId::from_counter(value : UInt64) -> StreamId {
  { text: value.to_string(), }
}

///|
pub impl Show for StreamId with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend StreamId with Show::{output, to_string}

///|
/// The public ID of a connection. It has 1 to 256 characters, and no control
/// or space characters.
#derive(Eq, Hash, Debug)
pub struct ConnectionId {
  priv text : String
}

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

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

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

///|
/// Parse a connection ID.
pub fn ConnectionId::parse(text : String) -> ConnectionId raise IdentifierError {
  check_text(ConnectionId, text, name_length_limit, no_space=true)
  { text, }
}

///|
pub impl Show for ConnectionId with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend ConnectionId with Show::{output, to_string}

///|
/// The private token of a connection. It has the rules of a connection ID.
/// `Show`, `Debug` and parse errors write `[REDACTED]` in place of the token.
/// Only the transport request that needs the token reads it with `expose`.
pub struct ConnectionToken {
  priv text : String
}

///|
/// Parse a connection token. A parse error holds `[REDACTED]`, not the text.
pub fn ConnectionToken::parse(
  text : String,
) -> ConnectionToken raise IdentifierError {
  check_text(
    ConnectionToken,
    text,
    name_length_limit,
    no_space=true,
    shown=redacted,
  )
  { text, }
}

///|
/// The token text. Use it only to build the transport request.
pub fn ConnectionToken::expose(self : ConnectionToken) -> String {
  self.text
}

///|
/// Two tokens are equal when their texts are equal.
pub impl Eq for ConnectionToken with fn equal(self, other) {
  self.text == other.text
}

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

///|
pub impl Hash for ConnectionToken with fn hash_combine(self, hasher) {
  hasher.combine(self.text)
}

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

///|
pub impl Show for ConnectionToken with fn output(_self, logger) {
  logger.write_string(redacted)
}

///|
pub extend ConnectionToken with Show::{output, to_string}

///|
pub impl @debug.Debug for ConnectionToken with fn to_repr(_self) {
  @debug.Repr(redacted)
}

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

///|
/// The ID of a user, from the identity of a connection. It has 1 to 256
/// characters and no control characters.
#derive(Eq, Hash, Debug)
pub struct UserId {
  priv text : String
}

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

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

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

///|
/// Parse a user ID.
pub fn UserId::parse(text : String) -> UserId raise IdentifierError {
  check_text(UserId, text, name_length_limit)
  { text, }
}

///|
pub impl Show for UserId with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend UserId with Show::{output, to_string}

///|
/// The name of a group of connections. It has 1 to 256 characters and no
/// control characters.
#derive(Eq, Hash, Debug)
pub struct GroupName {
  priv text : String
}

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

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

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

///|
/// Parse a group name.
pub fn GroupName::parse(text : String) -> GroupName raise IdentifierError {
  check_text(GroupName, text, name_length_limit)
  { text, }
}

///|
pub impl Show for GroupName with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend GroupName with Show::{output, to_string}

///|
/// The URL path of a hub endpoint, for example `/chat` or `/hubs/chat`. It starts
/// with `/`, has one or more nonempty segments, and holds only ASCII letters,
/// digits, `-`, `.`, `_` and `~` in a segment. It has at most 256 characters.
#derive(Eq, Hash, Debug)
pub struct EndpointPath {
  priv text : String
}

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

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

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

///|
/// Parse an endpoint path.
pub fn EndpointPath::parse(text : String) -> EndpointPath raise IdentifierError {
  check_text(EndpointPath, text, name_length_limit)
  guard text.has_prefix("/") else {
    raise InvalidIdentifier(kind=EndpointPath, text~, rule=NoLeadingSlash)
  }
  let mut previous = ' '
  for char in text {
    if char == '/' && previous == '/' {
      raise InvalidIdentifier(kind=EndpointPath, text~, rule=EmptySegment)
    }
    guard char == '/' ||
      is_ascii_letter(char) ||
      is_ascii_digit(char) ||
      char == '-' ||
      char == '.' ||
      char == '_' ||
      char == '~' else {
      raise InvalidIdentifier(
        kind=EndpointPath,
        text~,
        rule=CharNotAllowed(char),
      )
    }
    previous = char
  }
  guard previous != '/' else {
    raise InvalidIdentifier(kind=EndpointPath, text~, rule=EmptySegment)
  }
  { text, }
}

///|
/// The negotiate path: the endpoint path followed by `/negotiate`.
pub fn EndpointPath::negotiate(self : EndpointPath) -> String {
  self.text + "/negotiate"
}

///|
pub impl Show for EndpointPath with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend EndpointPath with Show::{output, to_string}

///|
/// The limit of the length of an access token.
pub let access_token_length_limit : Int32 = 16384

///|
/// A bearer access token, for example a JWT. It has 1 to 16384 characters, and
/// no control or space characters. `Show`, `Debug` and parse errors write
/// `[REDACTED]`. Only the request that sends the token reads it with `expose`.
pub struct AccessToken {
  priv text : String
}

///|
/// Parse an access token. A parse error holds `[REDACTED]`, not the text.
pub fn AccessToken::parse(text : String) -> AccessToken raise IdentifierError {
  check_text(
    AccessToken,
    text,
    access_token_length_limit,
    no_space=true,
    shown=redacted,
  )
  { text, }
}

///|
/// The token text. Use it only to build the request that sends it.
pub fn AccessToken::expose(self : AccessToken) -> String {
  self.text
}

///|
pub impl Eq for AccessToken with fn equal(self, other) {
  self.text == other.text
}

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

///|
pub impl Show for AccessToken with fn output(_self, logger) {
  logger.write_string(redacted)
}

///|
pub extend AccessToken with Show::{output, to_string}

///|
pub impl @debug.Debug for AccessToken with fn to_repr(_self) {
  @debug.Repr(redacted)
}

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