///|
/// A fault in the construction of a payload value.
#derive(Eq, Debug)
pub suberror HubValueError {
  /// A map got the key `key` a second time.
  DuplicateKey(key~ : String)
  /// A double is NaN or infinite, which no hub protocol encoding can write.
  NotFinite(value~ : Double)
}

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

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

///|
/// Text for people that describes the fault.
pub fn HubValueError::message(self : HubValueError) -> String {
  match self {
    DuplicateKey(key~) => "The map already has the key \{key.escape()}"
    NotFinite(value~) =>
      "The double \{value} is not finite; a payload value must be finite"
  }
}

///|
/// A finite double: not NaN and not infinite.
#derive(Eq, Compare, Hash, Debug)
pub struct FiniteDouble {
  priv value : Double
}

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

///|
pub extend FiniteDouble with Compare::{compare}

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

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

///|
/// Parse a finite double.
pub fn FiniteDouble::parse(value : Double) -> FiniteDouble raise HubValueError {
  guard !value.is_nan() && !value.is_inf() else { raise NotFinite(value~) }
  { value, }
}

///|
/// The double.
pub fn FiniteDouble::value(self : FiniteDouble) -> Double {
  self.value
}

///|
/// A map of a payload value: string keys in the order in which they were added,
/// each key one time. The value is immutable; `add` gives a new map.
#derive(Eq, Hash, Debug)
pub struct HubMap {
  priv entries : ReadOnlyArray[(String, HubValue)]
}

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

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

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

///|
/// The map with no keys.
pub fn HubMap::empty() -> HubMap {
  { entries: ReadOnlyArray::from_array([]), }
}

///|
/// The map of `entries`, in their order. A key that comes two times raises
/// `DuplicateKey` with that key.
pub fn HubMap::new(
  entries : ArrayView[(String, HubValue)],
) -> HubMap raise HubValueError {
  let seen : Map[String, Unit] = Map([])
  for entry in entries {
    guard !seen.contains(entry.0) else { raise DuplicateKey(key=entry.0) }
    seen[entry.0] = ()
  }
  { entries: ReadOnlyArray::from_array(entries), }
}

///|
/// A new map with the entries of `self` and then `key` with `value`. A key that
/// `self` has raises `DuplicateKey`.
pub fn HubMap::add(
  self : HubMap,
  key : String,
  value : HubValue,
) -> HubMap raise HubValueError {
  guard !self.entries.iter().any(entry => entry.0 == key) else {
    raise DuplicateKey(key~)
  }
  let entries = self.entries.iter().collect()
  entries.push((key, value))
  { entries: ReadOnlyArray::from_array(entries), }
}

///|
/// The value of `key`.
pub fn HubMap::get(self : HubMap, key : String) -> HubValue? {
  for entry in self.entries {
    if entry.0 == key {
      return Some(entry.1)
    }
  }
  None
}

///|
/// The value of `key`. When no key is equal to `key`, the first key that is
/// equal to it with no regard to case. This is the property match of
/// System.Text.Json with `PropertyNameCaseInsensitive`.
pub fn HubMap::get_ignore_case(self : HubMap, key : String) -> HubValue? {
  match self.get(key) {
    Some(value) => Some(value)
    None => {
      let lower = key.to_lower()
      for entry in self.entries {
        if entry.0.to_lower() == lower {
          return Some(entry.1)
        }
      }
      None
    }
  }
}

///|
/// The entries in the order in which they were added.
pub fn HubMap::iter(self : HubMap) -> Iter[(String, HubValue)] {
  self.entries.iter()
}

///|
/// The keys in the order in which they were added.
pub fn HubMap::keys(self : HubMap) -> Array[String] {
  self.entries.iter().map(entry => entry.0).collect()
}

///|
/// The number of keys.
pub fn HubMap::length(self : HubMap) -> Int32 {
  self.entries.length()
}

///|
/// A payload value that each hub protocol encoding can write completely
/// (design CDC-1). Arguments, stream items and results pass through this tree.
#derive(Eq, Hash, Debug)
pub(all) enum HubValue {
  Null
  Bool(Bool)
  /// A signed 64-bit integer.
  Int(Int64)
  /// An unsigned 64-bit integer.
  UInt(UInt64)
  Double(FiniteDouble)
  String(String)
  /// Bytes. The JSON encoding writes them as Base64 text.
  Bytes(Bytes)
  /// An instant. The JSON encoding writes it as ISO 8601 text in UTC.
  Timestamp(Timestamp)
  Array(ReadOnlyArray[HubValue])
  Map(HubMap)
}

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

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

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

///|
/// The array value of `items`.
pub fn HubValue::array(items : ArrayView[HubValue]) -> HubValue {
  Array(ReadOnlyArray::from_array(items))
}

///|
/// The kind of a payload value, for error texts.
#derive(Eq, Debug)
pub(all) enum ValueKind {
  Null
  Bool
  Integer
  Double
  String
  Bytes
  Timestamp
  Array
  Map
}

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

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

///|
/// The kind of `self`. `Int` and `UInt` are both `Integer`.
pub fn HubValue::kind(self : HubValue) -> ValueKind {
  match self {
    Null => Null
    Bool(_) => Bool
    Int(_) | UInt(_) => Integer
    Double(_) => Double
    String(_) => String
    Bytes(_) => Bytes
    Timestamp(_) => Timestamp
    Array(_) => Array
    Map(_) => Map
  }
}

///|
/// The name of the kind for people, for example `an integer`.
pub fn ValueKind::label(self : ValueKind) -> String {
  match self {
    Null => "null"
    Bool => "a boolean"
    Integer => "an integer"
    Double => "a number"
    String => "a string"
    Bytes => "bytes"
    Timestamp => "a timestamp"
    Array => "an array"
    Map => "an object"
  }
}