///|
/// How a property behaves on the objects of a type. What is missing comes from the metadata of the base type.
pub struct PropertyMetadata[T] {
  priv default_value : T?
  priv changed : ((DependencyObject, DependencyProperty[T], T, T) -> Unit raise)?
  priv coerce : ((DependencyObject, T) -> T raise)?
  priv inherits : Bool?
  priv logical_content : ((T) -> DependencyObject?)?
}

///|
/// Metadata to register a property with, or to give it for another type.
///
/// - `default_value` is the value of objects on which nothing is set. A registration has it as its own argument, and fails
///   when it is here.
/// - `changed` runs after each change of the effective value, with the object, the property, the old value and the new one.
///   It does not replace the one of the base type, which runs first.
/// - `coerce` computes the effective value from the value that is set. It can read and change other properties of the
///   object. Its result is not validated.
/// - `inherits` says that elements on which nothing is set use the value of their logical ancestors.
/// - `logical_content` gives the element in a value. It becomes a logical child of the object, before `changed` runs.
pub fn[T] PropertyMetadata::new(
  default_value? : T,
  changed? : (DependencyObject, DependencyProperty[T], T, T) -> Unit raise,
  coerce? : (DependencyObject, T) -> T raise,
  inherits? : Bool,
  logical_content? : (T) -> DependencyObject?,
) -> PropertyMetadata[T] {
  { default_value, changed, coerce, inherits, logical_content, }
}

///|
/// The metadata of a property for a type, merged and without the value type. The functions get the property as an argument
/// and do not hold it, because the property holds them.
priv struct Metadata {
  default_value : AnyValue
  changed : Array[
    (DependencyObject, PropertyInfo, AnyValue, AnyValue) -> Unit raise,
  ]
  coerce : ((DependencyObject, AnyValue) -> AnyValue raise)?
  inherits : Bool
  logical_content : (AnyValue) -> DependencyObject?
}

///|
/// The metadata of a property that was registered without any.
fn Metadata::new(default_value : AnyValue) -> Metadata {
  {
    default_value,
    changed: [],
    coerce: None,
    inherits: false,
    logical_content: _ => None,
  }
}

///|
/// This metadata over that of the base type. The `changed` functions of `base` run first, and what is missing here comes
/// from `base`.
fn[T] PropertyMetadata::merge(
  self : PropertyMetadata[T],
  base : Metadata,
  key : ValueKey[T],
) -> Metadata {
  {
    default_value: match self.default_value {
      Some(value) => key.wrap(value)
      None => base.default_value
    },
    changed: match self.changed {
      Some(changed) =>
        [
          ..base.changed,
          (object, info, old, new) => {
            changed(
              object,
              { info, key, },
              key.value_of(old),
              key.value_of(new),
            )
          },
        ]
      None => base.changed
    },
    coerce: match self.coerce {
      Some(coerce) =>
        Some((object, value) => key.wrap(coerce(object, key.value_of(value))))
      None => base.coerce
    },
    inherits: self.inherits.unwrap_or(base.inherits),
    logical_content: match self.logical_content {
      Some(content) => value => content(key.value_of(value))
      None => base.logical_content
    },
  }
}

///|
/// The metadata for objects of the type `owner`: that of the type, or of the nearest base type that has some, or else the
/// default metadata.
fn PropertyInfo::metadata(self : PropertyInfo, owner : OwnerType) -> Metadata {
  if self.overrides.is_empty() {
    return self.default_metadata
  }
  owner
  .find_base(owner => self.overrides.get(owner))
  .unwrap_or(self.default_metadata)
}

///|
/// Give the property metadata for objects of the type `owner` and of the types that derive from it. `key` is needed for a
/// read-only property.
///
/// This works once for each type, and the registration does it already for the type of a property with metadata and of a
/// read-only one that is not attached. The metadata of the base type is merged at this moment. Do this before there are
/// objects of the type: an object keeps the values that it has stored, and nothing is notified.
pub fn[T] DependencyProperty::override_metadata(
  self : DependencyProperty[T],
  owner : OwnerType,
  metadata : PropertyMetadata[T],
  key? : DependencyPropertyKey[T],
) -> Unit raise DependencyError {
  let info = self.info
  info.check_metadata_type(owner)
  info.check_key(key.map(key => key.info()))
  let base = match owner.base {
    Some(base) => info.metadata(base)
    None => info.default_metadata
  }
  let merged = metadata.merge(base, self.key)
  // WPF also validates before it looks whether the type has metadata already.
  if metadata.default_value is Some(_) && !(info.validate)(merged.default_value) {
    raise InvalidRegistration(
      "\{(info.show)(merged.default_value)} is not a valid default value of `\{info}` for `\{owner}`",
    )
  }
  if info.overrides.contains(owner) {
    raise InvalidRegistration("`\{info}` has metadata for `\{owner}` already")
  }
  info.overrides[owner] = merged
}

///|
/// The metadata of a property that is in force for a type.
pub struct MergedMetadata[T] {
  priv metadata : Metadata
  priv key : ValueKey[T]
}

///|
/// The metadata for objects of the type `owner`.
pub fn[T] DependencyProperty::get_metadata(
  self : DependencyProperty[T],
  owner : OwnerType,
) -> MergedMetadata[T] raise DependencyError {
  self.info.check_metadata_type(owner)
  { metadata: self.info.metadata(owner), key: self.key, }
}

///|
pub fn[T] MergedMetadata::default_value(self : MergedMetadata[T]) -> T {
  self.key.value_of(self.metadata.default_value)
}

///|
pub fn[T] MergedMetadata::inherits(self : MergedMetadata[T]) -> Bool {
  self.metadata.inherits
}

///|
/// The element in `value` that becomes a logical child of the object.
pub fn[T] MergedMetadata::logical_content(
  self : MergedMetadata[T],
  value : T,
) -> DependencyObject? {
  (self.metadata.logical_content)(self.key.wrap(value))
}

///|
/// Fail when `owner` is a type of another registry.
fn PropertyInfo::check_metadata_type(
  self : PropertyInfo,
  owner : OwnerType,
) -> Unit raise DependencyError {
  if owner.registry_id != self.registry_id {
    raise RegistryMismatch(
      "`\{self}` has no metadata for `\{owner}`, which belongs to another registry",
    )
  }
}