///|
/// A dynamic value in a XAML node stream and in the members of loaded objects (design D2).
///
/// The numeric cases are distinct, as .NET's boxed primitives are: `Int(1)` is not `Int64(1)`.
/// `Char` holds one UTF-16 code unit, as `System.Char` does (F24). `List` holds a read-only array,
/// so a value can be shared without copying. `Object` holds a handle to an object that registered
/// code created; `x:Decimal`, `x:TimeSpan` and `x:Uri` values are handles of those types (D12).
///
/// Equality treats NaN as equal to NaN, as .NET `Double.Equals` and `Single.Equals` do, and `0.0`
/// as equal to `-0.0` (F52). Equality, hashing and debug output walk lists with explicit work stacks, so deeply
/// nested lists cannot overflow a target's stack (2F18).
pub(all) enum XamlValue {
  Null
  Bool(Bool)
  Byte(Byte)
  Int16(Int16)
  Int(Int32)
  Int64(Int64)
  Single(Float)
  Double(Double)
  Char(UInt16)
  String(String)
  List(ReadOnlyArray[XamlValue])
  Object(XamlObject)
}

///|
pub impl Eq for XamlValue with fn equal(self, other) {
  let pending = [(self, other)]
  while pending.pop() is Some(pair) {
    let same = match pair {
      (Null, Null) => true
      (Bool(a), Bool(b)) => a == b
      (Byte(a), Byte(b)) => a == b
      (Int16(a), Int16(b)) => a == b
      (Int(a), Int(b)) => a == b
      (Int64(a), Int64(b)) => a == b
      (Single(a), Single(b)) => a == b || (a.is_nan() && b.is_nan())
      (Double(a), Double(b)) => a == b || (a.is_nan() && b.is_nan())
      (Char(a), Char(b)) => a == b
      (String(a), String(b)) => a == b
      (Object(a), Object(b)) => a == b
      (List(a), List(b)) =>
        if physical_equal(a, b) {
          true
        } else if a.length() != b.length() {
          false
        } else {
          for i, item in a {
            pending.push((item, b[i]))
          }
          true
        }
      _ => false
    }
    if !same {
      return false
    }
  }
  true
}

///|
pub impl Hash for XamlValue with fn hash_combine(self, hasher) {
  // Pre-order with list lengths, so different trees feed different sequences.
  let pending = [self]
  while pending.pop() is Some(value) {
    match value {
      Null => hasher.combine_int(0)
      Bool(b) => {
        hasher.combine_int(1)
        hasher.combine_bool(b)
      }
      Int(i) => {
        hasher.combine_int(2)
        hasher.combine_int(i)
      }
      Int64(i) => {
        hasher.combine_int(3)
        hasher.combine_int64(i)
      }
      Double(d) => {
        hasher.combine_int(4)
        combine_float(hasher, d)
      }
      Byte(b) => {
        hasher.combine_int(8)
        hasher.combine_byte(b)
      }
      Int16(i) => {
        hasher.combine_int(9)
        hasher.combine_int(i.to_int())
      }
      Single(f) => {
        hasher.combine_int(10)
        combine_float(hasher, f.to_double())
      }
      Char(unit) => {
        hasher.combine_int(11)
        hasher.combine_int(unit.to_int())
      }
      String(s) => {
        hasher.combine_int(5)
        hasher.combine_string(s)
      }
      List(items) => {
        hasher.combine_int(6)
        hasher.combine_int(items.length())
        for i = items.length() - 1; i >= 0; i = i - 1 {
          pending.push(items[i])
        }
      }
      Object(handle) => {
        hasher.combine_int(7)
        hasher.combine(handle)
      }
    }
  }
}

///|
/// Combine a floating-point value so that values that compare equal hash alike: every NaN, and
/// `0.0` with `-0.0`.
fn combine_float(hasher : Hasher, d : Double) -> Unit {
  if d.is_nan() {
    hasher.combine_int(-1)
  } else if d == 0.0 {
    hasher.combine_double(0.0)
  } else {
    hasher.combine_double(d)
  }
}

///|
priv enum ValueText {
  Value(XamlValue)
  Text(String)
}

///|
/// The value as constructor syntax, such as `List([Int(1), String("a")])`, built with an explicit
/// work stack.
fn XamlValue::debug_text(self : XamlValue) -> String {
  let buffer = StringBuilder()
  let pending = [ValueText::Value(self)]
  while pending.pop() is Some(part) {
    match part {
      Text(text) => buffer.write_string(text)
      Value(Null) => buffer.write_string("Null")
      Value(Bool(b)) => buffer.write_string("Bool(\{b})")
      Value(Int(i)) => buffer.write_string("Int(\{i})")
      Value(Int64(i)) => buffer.write_string("Int64(\{i})")
      Value(Double(d)) => buffer.write_string("Double(\{d})")
      Value(Byte(b)) => buffer.write_string("Byte(\{b.to_int()})")
      Value(Int16(i)) => buffer.write_string("Int16(\{i})")
      Value(Single(f)) => buffer.write_string("Single(\{f})")
      Value(Char(unit)) => {
        let hex = unit.to_int().to_string(radix=16).to_upper()
        buffer.write_string("Char(U+")
        buffer.write_view("0000"[:4 - hex.length()])
        buffer.write_string(hex)
        buffer.write_char(')')
      }
      Value(String(s)) => buffer.write_string("String(\{@debug.to_string(s)})")
      Value(Object(handle)) =>
        buffer.write_string("Object(\{handle.type_name})")
      Value(List(items)) => {
        buffer.write_string("List([")
        pending.push(Text("])"))
        for i = items.length() - 1; i >= 0; i = i - 1 {
          pending.push(Value(items[i]))
          if i > 0 {
            pending.push(Text(", "))
          }
        }
      }
    }
  }
  buffer.to_string()
}

///|
/// The constructor syntax of the value as one flat literal.
pub impl Debug for XamlValue with fn to_repr(self) {
  @debug.Repr::literal(self.debug_text())
}

///|
/// A handle to an object that registered code created: the runtime XAML type of the object, the key
/// that wrapped it and an opaque payload.
///
/// MoonBit has no `Any` type and no downcasts. The payload is a closure that stores the object in
/// the slot of the `ObjectKey[T]` that wrapped it, so only code that holds that key can read the
/// object back as a `T`. Each handle records the key that made it, so another key never runs the
/// payload. Two handles are equal when they have the same type and key and their objects are equal
/// by the key's equality: by default the same object, or the `equal` function given to the key.
/// A key with an `equal` function classifies its handles as values, which saving writes inline and
/// never shares, as .NET value types are copied (F17).
pub struct XamlObject {
  type_name : XamlTypeName
  priv key_id : Int32
  priv payload : () -> Unit
  priv same_as : (XamlObject) -> Bool
  priv value_semantics : Bool
  priv hash_of : () -> Int32?
}

///|
pub impl Eq for XamlObject with fn equal(self, other) {
  // A search through many objects mostly compares different ones, which the object tells faster than the name.
  (self.same_as)(other) && self.type_name == other.type_name
}

///|
/// Equal handles have the same type and key, and their objects hash alike by the key's hash when it
/// has one, so the hash combines those.
pub impl Hash for XamlObject with fn hash_combine(self, hasher) {
  hasher.combine(self.type_name)
  hasher.combine_int(self.key_id)
  if (self.hash_of)() is Some(h) {
    hasher.combine_int(h)
  }
}

///|
pub impl Debug for XamlObject with fn to_repr(self) {
  @debug.Repr(XamlObjectRepr::{ type_name: self.type_name, })
}

///|
/// What a handle shows in debug output: the payload is opaque.
#derive(Debug)
priv struct XamlObjectRepr {
  type_name : XamlTypeName
}

///|
/// The runtime type that a handle names.
pub fn XamlObject::type_name(self : XamlObject) -> XamlTypeName {
  self.type_name
}

///|
/// The identity of the key that wrapped the object. Handles of different keys are never the same
/// object.
pub fn XamlObject::key_id(self : XamlObject) -> Int32 {
  self.key_id
}

///|
/// Whether the key that wrapped the object compares by value, so the handle stands for a value
/// rather than a shared object (F17).
pub fn XamlObject::is_value(self : XamlObject) -> Bool {
  self.value_semantics
}

///|
/// The key's hash of the object, consistent with the key's equality, or `None` when the key has no
/// hash (F5). Identity tables index by key and hash and search linearly without one.
pub fn XamlObject::object_hash(self : XamlObject) -> Int32? {
  (self.hash_of)()
}

///|
/// A key that wraps values of type `T` in `XamlObject` handles and reads them back.
///
/// Registration code creates one key for each MoonBit type that it exposes to XAML.
pub struct ObjectKey[T] {
  priv id : Int32
  priv slot : Ref[T?]
  priv equal : ((T, T) -> Bool)?
  priv hash : ((T) -> Int32)?
}

///|
/// The last key id handed out. Ids tell keys apart without running payloads.
let last_key_id : Ref[Int32] = Ref(0)

///|
/// A new key. `equal` decides when two wrapped objects are equal, and makes the handles values;
/// without it, handles are equal only when they wrap the same object. `hash` must give equal hashes
/// for objects that the key treats as equal: the same object, or objects that `equal` accepts.
pub fn[T] ObjectKey::new(
  equal? : (T, T) -> Bool,
  hash? : (T) -> Int32,
) -> ObjectKey[T] {
  last_key_id.val += 1
  { id: last_key_id.val, slot: Ref(None), equal, hash, }
}

///|
/// The identity of the key, which `XamlObject::key_id` gives for its handles.
pub fn[T] ObjectKey::id(self : ObjectKey[T]) -> Int32 {
  self.id
}

///|
/// Wrap `value` as an object of the XAML type `type_name`.
pub fn[T] ObjectKey::wrap(
  self : ObjectKey[T],
  type_name : XamlTypeName,
  value : T,
) -> XamlObject {
  let slot = self.slot
  let same_as = other => {
    match self.unwrap(other) {
      Some(other_value) =>
        match self.equal {
          Some(equal) => equal(value, other_value)
          None => physical_equal(value, other_value)
        }
      None => false
    }
  }
  let hash = self.hash
  {
    type_name,
    key_id: self.id,
    payload: () => slot.val = Some(value),
    same_as,
    value_semantics: self.equal is Some(_),
    hash_of: () => hash.map(h => h(value)),
  }
}

///|
/// The object in `handle` when this key wrapped it, else `None`.
pub fn[T] ObjectKey::unwrap(self : ObjectKey[T], handle : XamlObject) -> T? {
  if handle.key_id != self.id {
    return None
  }
  (handle.payload)()
  let value = self.slot.val
  self.slot.val = None
  value
}

///|
/// A list value with a copy of `items`.
pub fn XamlValue::list(items : ArrayView[XamlValue]) -> XamlValue {
  List(ReadOnlyArray::from_array(items))
}