///|
/// Where the base value of a property comes from.
#derive(Eq)
priv enum Source {
  Default
  /// The nearest ancestor on which the property inherits.
  Inherited
  Local
}

///|
/// What replaces the base value as the effective value.
priv enum Modifier {
  Unmodified
  /// The value of `set_current_value`. It is read as a local value.
  Current(AnyValue)
  /// The result of a coercion that changed the value.
  Coerced(AnyValue)
}

///|
/// The value of a property on an object. An object stores it when it is more than the default value.
priv struct StoredValue {
  property : PropertyInfo
  source : Source
  base : AnyValue
  modifier : Modifier
  /// What the parent supplies, for the elements below this one. It is here when the property does not inherit on the object.
  passed : AnyValue?
}

///|
/// What an object has that stores nothing for the property.
fn Metadata::unset(self : Metadata, property : PropertyInfo) -> StoredValue {
  {
    property,
    source: Default,
    base: self.default_value,
    modifier: Unmodified,
    passed: None,
  }
}

///|
/// Whether this is just the default value, so that the object does not supply it to the elements below it.
fn StoredValue::is_default(self : StoredValue) -> Bool {
  self is { source: Default, modifier: Unmodified, .. }
}

///|
/// Whether this is what an object has that stores nothing. `make_room` stores such values, and some stay when an error or a handler
/// ends the evaluation.
fn StoredValue::is_unset(self : StoredValue) -> Bool {
  self.is_default() && self.passed is None
}

///|
fn StoredValue::effective(self : StoredValue) -> AnyValue {
  match self.modifier {
    Unmodified => self.base
    Current(value) | Coerced(value) => value
  }
}

///|
/// The current value, or else the local value.
fn StoredValue::local_value(self : StoredValue) -> AnyValue? {
  match self {
    { modifier: Current(value), .. } => Some(value)
    { source: Local, base, .. } => Some(base)
    { source: Default | Inherited, .. } => None
  }
}

///|
/// The position of the property in `values`, or the one at which to insert it.
fn DependencyObject::find(
  self : DependencyObject,
  property : PropertyInfo,
) -> Result[Int32, Int32] {
  self.values.binary_search_by(value => {
    value.property.index.compare(property.index)
  })
}

///|
/// What the object stores for the property, when this is more than the default value.
fn DependencyObject::stored(
  self : DependencyObject,
  property : PropertyInfo,
) -> StoredValue? {
  match self.find(property) {
    Ok(i) if !self.values[i].is_unset() => Some(self.values[i])
    _ => None
  }
}

///|
/// Store `value`, or nothing when it is just the default value and no value passes.
fn DependencyObject::store(
  self : DependencyObject,
  value : StoredValue,
) -> Unit {
  let keep = !value.is_unset()
  let values = self.values
  // Most objects have few values that are set rarely, so the array has no room for more. An array with room would also hold
  // on to a removed value, and native and wasm would then not free an object that was its own value.
  match self.find(value.property) {
    Ok(i) if keep => values[i] = value
    Ok(i) =>
      self.values = FixedArray::makei(values.length() - 1, j => {
        if j < i {
          values[j]
        } else {
          values[j + 1]
        }
      })
    Err(i) if keep =>
      self.values = FixedArray::makei(values.length() + 1, j => {
        if j < i {
          values[j]
        } else if j > i {
          values[j - 1]
        } else {
          value
        }
      })
    Err(_) => ()
  }
}

///|
/// An operation on the value of a property.
priv enum Change {
  Set(AnyValue)
  SetCurrent(AnyValue)
  Clear
  Coerce
  /// Take what the ancestors supply now.
  Inherit
}

///|
/// Make `change`, and then pass the value on to the elements below. All operations do this after their checks of the registry
/// and of the key.
fn DependencyObject::change(
  self : DependencyObject,
  property : PropertyInfo,
  change : Change,
) -> Unit raise {
  enter(() => "\{property}")
  defer leave()
  if self.update(property, change) {
    self.walk(element => element.update(property, Inherit))
  }
}

///|
/// Make `change` on this object alone. This is the only function that changes a value. Returns whether it can change the values
/// of the elements below.
///
/// The steps and their order are those of `UpdateEffectiveValue` in WPF. The new value is stored after the coercion and
/// before the comparison with the old value. An error of a callback keeps what is stored at that moment.
fn DependencyObject::update(
  self : DependencyObject,
  property : PropertyInfo,
  change : Change,
) -> Bool raise {
  let metadata = property.metadata(self.owner_type)
  let stored = self.stored(property)
  let change = match (change, stored) {
    // To coerce a current value is to set it again, as in WPF.
    (Coerce, Some({ modifier: Current(value), .. })) => SetCurrent(value)
    // The value passes through an element on which the property does not inherit.
    (Inherit, _) if !metadata.inherits => {
      let passed = self.inherited(property)
      self.store({ ..stored.unwrap_or(metadata.unset(property)), passed, })
      return true
    }
    (Inherit, Some({ source: Local, .. })) => return false
    _ => change
  }
  if change is (Set(value) | SetCurrent(value)) {
    property.check_value(value)
  }
  let default_value = metadata.unset(property)
  let old = self.stored(property).unwrap_or(default_value)
  let inherited = if metadata.inherits {
    self.inherited(property)
  } else {
    None
  }
  let new = match change {
    Set(value) => { ..old, source: Local, base: value, modifier: Unmodified, }
    SetCurrent(value) if !property.equal_values(value, old.base) =>
      { ..old, modifier: Current(value), }
    SetCurrent(_) | Coerce => { ..old, modifier: Unmodified, }
    Clear | Inherit =>
      match inherited {
        Some(base) => { ..default_value, source: Inherited, base, }
        None => default_value
      }
  }
  let new = match metadata.coerce {
    Some(coerce) if !(change is Clear && new.source is Default) => {
      let value = new.effective()
      let coerced = coerce(self, value)
      if metadata.inherits &&
        new.source != Local &&
        !property.same_supply(inherited, self.inherited(property)) {
        // The coercion has changed what the object inherits, so `new` is out of date.
        enter(() => "\{property}")
        defer leave()
        return self.update(property, change)
      }
      if property.equal_values(coerced, value) {
        new
      } else {
        { ..new, modifier: Coerced(coerced), }
      }
    }
    _ => new
  }
  if metadata.inherits {
    self.store(new)
  } else {
    // The coercion can have changed what passes.
    let passed = self.stored(property).bind(value => value.passed)
    self.store({ ..new, passed, })
  }
  let old_value = old.effective()
  let new_value = new.effective()
  let changed = !property.equal_values(old_value, new_value)
  if changed {
    self.notify(property, metadata, old_value, new_value)
  }
  // As in WPF, another source of an equal value is a change for the elements below.
  metadata.inherits &&
  (changed || old.source != new.source || old.is_default() != new.is_default())
}