///|
/// The host value of an object. It can be set only once, so a released host is not the same as none.
priv enum Host {
  NotSet
  Present(AnyValue)
  Released
}

///|
/// An object whose property values this package stores and resolves.
///
/// MoonBit has no struct inheritance. A type such as `Button` has a dependency object in a field, made for the owner type
/// `Button`, where a WPF control derives from `DependencyObject`.
pub struct DependencyObject {
  priv number : Int32
  priv registry : PropertyRegistry
  priv owner_type : OwnerType
  /// In the order of the registration of the properties.
  priv mut values : FixedArray[StoredValue]
  /// A new handler is added to the array, and a removal makes a new one, so that a notification still has all handlers that it
  /// started with.
  priv mut handlers : Array[ChangeHandler]
  priv mut host : Host
  priv mut extensions : Array[AnyValue]?
  priv mut parent : DependencyObject?
  /// The logical children of the parent before and after this one.
  priv mut previous : DependencyObject?
  priv mut next : DependencyObject?
  priv mut children : Children?
}

///|
/// Nothing is added to these arrays, so all objects share them while they have no values or no handlers.
let no_values : FixedArray[StoredValue] = []

///|
let no_handlers : Array[ChangeHandler] = []

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

///|
/// A new object of the type `owner`, which belongs to `registry`.
pub fn DependencyObject::new(
  owner : OwnerType,
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> DependencyObject raise DependencyError {
  registry.check_owner(owner)
  last_object.val += 1
  {
    number: last_object.val,
    registry,
    owner_type: owner,
    values: no_values,
    handlers: no_handlers,
    host: NotSet,
    extensions: None,
    parent: None,
    previous: None,
    next: None,
    children: None,
  }
}

///|
/// Two dependency objects are equal when they are the same object.
pub impl Eq for DependencyObject with fn equal(self, other) {
  physical_equal(self, other)
}

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

///|
/// The name of the type and the number of the object in the order of creation.
pub impl Debug for DependencyObject with fn to_repr(self) {
  @debug.Repr::literal("\{self.owner_type}#\{self.number}")
}

///|
/// The registry that has the type of the object and the properties that can be used with it.
pub fn DependencyObject::registry(self : DependencyObject) -> PropertyRegistry {
  self.registry
}

///|
pub fn DependencyObject::registry_id(self : DependencyObject) -> RegistryId {
  self.registry.id
}

///|
pub fn DependencyObject::owner_type(self : DependencyObject) -> OwnerType {
  self.owner_type
}

///|
/// Connect the object with the value that embeds it, such as a `Button`, so that code that has only the object gets the
/// `Button` with `host`. This works once, also after `release_host`.
pub fn DependencyObject::set_host(
  self : DependencyObject,
  host : AnyValue,
) -> Unit raise DependencyError {
  guard self.host is NotSet else {
    raise HostAlreadySet(
      "the host value of a `\{self.owner_type}` object can be set only once",
    )
  }
  self.host = Present(host)
}

///|
/// The value that embeds the object.
pub fn DependencyObject::host(self : DependencyObject) -> AnyValue? {
  match self.host {
    Present(host) => Some(host)
    NotSet | Released => None
  }
}

///|
/// Let go of the host value. The host and the object hold each other, and native and wasm do not free such a circle.
pub fn DependencyObject::release_host(self : DependencyObject) -> Unit {
  if self.host is Present(_) {
    self.host = Released
  }
}

///|
/// The data that a package keeps on the object under its own key.
pub fn[T] DependencyObject::extension(
  self : DependencyObject,
  key : ValueKey[T],
) -> T? {
  match self.extensions {
    Some(items) => extension_of(items, key)
    None => None
  }
}

///|
/// Keep `value` on the object under `key`, in the place of the value that was there. This is not a property: it has no
/// metadata and notifies nothing.
pub fn[T] DependencyObject::set_extension(
  self : DependencyObject,
  key : ValueKey[T],
  value : T,
) -> Unit {
  match self.extensions {
    Some(items) => set_extension_of(items, key, value)
    None => self.extensions = Some([key.wrap(value)])
  }
}

///|
/// Let go of the value under `key`, when there is one.
pub fn[T] DependencyObject::remove_extension(
  self : DependencyObject,
  key : ValueKey[T],
) -> Unit {
  guard self.extensions is Some(items) else { return }
  // A new list, because `Array::remove` leaves the item in the memory of the old one.
  let others = items.filter(item => item.key_id != key.id)
  self.extensions = if others.is_empty() { None } else { Some(others) }
}