///|
/// The identity of a `ValueKey`. Its text is the name of the key.
pub struct ValueKeyId {
  priv number : Int32
  priv name : String
}

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

///|
pub impl Hash for ValueKeyId with fn hash_combine(self, hasher) {
  hasher.combine_int(self.number)
}

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

///|
pub extend ValueKeyId with Show::{to_string}

///|
pub impl Debug for ValueKeyId with fn to_repr(self) {
  @debug.Repr::literal(self.name)
}

///|
/// A value of any type, which only the key that wrapped it gives back.
///
/// MoonBit has no `Any` type and no downcasts. The payload is a closure that puts the value in the slot of its key. An
/// `AnyValue` has no equality, because equality belongs to the property: see `PropertyInfo::equal_values`.
pub struct AnyValue {
  priv key_id : ValueKeyId
  priv payload : () -> Unit
}

///|
/// The identity of the key that wrapped the value.
pub fn AnyValue::key_id(self : AnyValue) -> ValueKeyId {
  self.key_id
}

///|
/// A key that wraps values of type `T` as `AnyValue` and reads them back.
///
/// Keys that were made separately for one type do not read the values of each other. Use the shared keys of this
/// package, such as `double_key`, for the primitive types, and make one key for each type of your own.
pub struct ValueKey[T] {
  priv id : ValueKeyId
  priv slot : Ref[T?]
  priv equal : (T, T) -> Bool
  priv show : ((T) -> String)?
}

///|
let last_key : Ref[Int32] = Ref(0)

///|
fn[T] ValueKey::with_equal(
  name : String,
  equal : (T, T) -> Bool,
  show : ((T) -> String)?,
) -> ValueKey[T] {
  last_key.val += 1
  { id: { number: last_key.val, name, }, slot: Ref(None), equal, show, }
}

///|
/// A new key whose values are equal by `==`. Error messages show a value with `show`, or with `name` when it is omitted.
pub fn[T : Eq] ValueKey::new(
  name : String,
  show? : (T) -> String,
) -> ValueKey[T] {
  ValueKey::with_equal(name, (a, b) => a == b, show)
}

///|
/// A new key whose values are equal only when they are the same object, as WPF compares the values of reference types.
pub fn[T] ValueKey::by_identity(
  name : String,
  show? : (T) -> String,
) -> ValueKey[T] {
  ValueKey::with_equal(name, (a, b) => physical_equal(a, b), show)
}

///|
/// The identity of the key, which `AnyValue::key_id` gives for its values.
pub fn[T] ValueKey::id(self : ValueKey[T]) -> ValueKeyId {
  self.id
}

///|
/// Wrap `value` as a value of any type.
pub fn[T] ValueKey::wrap(self : ValueKey[T], value : T) -> AnyValue {
  let slot = self.slot
  { key_id: self.id, payload: () => slot.val = Some(value), }
}

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

///|
/// The value in `any`, which this key has wrapped.
fn[T] ValueKey::value_of(self : ValueKey[T], any : AnyValue) -> T {
  guard self.unwrap(any) is Some(value) else {
    abort("a `\{any.key_id}` value is read with the key `\{self.id}`")
  }
  value
}

///|
/// The text of `value` for an error message.
fn[T] ValueKey::text(self : ValueKey[T], value : T) -> String {
  match self.show {
    Some(show) => show(value)
    None => "a `\{self.id}` value"
  }
}

///|
/// The key of `Bool` values.
pub let bool_key : ValueKey[Bool] = ValueKey::new("Bool", show=v => "\{v}")

///|
/// The key of `Byte` values.
pub let byte_key : ValueKey[Byte] = ValueKey::new("Byte", show=v => "\{v}")

///|
/// The key of `Int16` values.
pub let int16_key : ValueKey[Int16] = ValueKey::new("Int16", show=v => "\{v}")

///|
/// The key of `Int` values.
pub let int_key : ValueKey[Int32] = ValueKey::new("Int", show=v => "\{v}")

///|
/// The key of `Int64` values.
pub let int64_key : ValueKey[Int64] = ValueKey::new("Int64", show=v => "\{v}")

///|
/// The key of `Float` values. Two NaNs are equal, as in .NET.
pub let float_key : ValueKey[Float] = ValueKey::with_equal(
  "Float",
  (a, b) => a == b || (a.is_nan() && b.is_nan()),
  Some(v => "\{v}"),
)

///|
/// The key of `Double` values. Two NaNs are equal, as in .NET.
pub let double_key : ValueKey[Double] = ValueKey::with_equal(
  "Double",
  (a, b) => a == b || (a.is_nan() && b.is_nan()),
  Some(v => "\{v}"),
)

///|
/// The key of `Char` values.
pub let char_key : ValueKey[Char] = ValueKey::new("Char", show=v => {
  @debug.to_string(v)
})

///|
/// The key of `String` values.
pub let string_key : ValueKey[String] = ValueKey::new("String", show=v => {
  @debug.to_string(v)
})

///|
/// The key of `Unit`, for things without data.
pub let unit_key : ValueKey[Unit] = ValueKey::new("Unit", show=v => "\{v}")

///|
/// The key of dependency objects. Two of them are equal when they are the same object.
pub let object_key : ValueKey[DependencyObject] = ValueKey::new(
  "DependencyObject",
  show=v => @debug.to_string(v),
)

///|
/// The value under `key`. The lists are short, so a search is enough.
fn[T] extension_of(items : Array[AnyValue], key : ValueKey[T]) -> T? {
  match items.search_by(item => item.key_id == key.id) {
    Some(i) => key.unwrap(items[i])
    None => None
  }
}

///|
/// Put `value` under `key`, in the place of the value that was there.
fn[T] set_extension_of(
  items : Array[AnyValue],
  key : ValueKey[T],
  value : T,
) -> Unit {
  match items.search_by(item => item.key_id == key.id) {
    Some(i) => items[i] = key.wrap(value)
    None => items.push(key.wrap(value))
  }
}