// Object keys of types with instance operations and base views between them (design D8, 2F3).

///|
/// A begin or end initialization callback on an object, as .NET `ISupportInitialize` (design D25).
pub type InitializationCallback = (@nodes.XamlObject) -> Unit raise

///|
/// An adapter from handles of one key to handles of a base type's key over the same instance.
priv struct BaseView {
  from_key : Int32
  to_key : Int32
  adapt : (@nodes.XamlObject) -> @nodes.XamlObject?
}

///|
/// Register the key that wraps objects of the type, so that `build()` can check that every
/// inherited operation reaches the instance (design D3, D8). A type without a key of its own uses
/// its base type's key. A type with instance operations (constructors, factory methods, setters,
/// getters, adders, enumerators or callbacks) registers one, or shares its base type's.
pub fn[T] XamlTypeDefinition::object_key(
  self : XamlTypeDefinition,
  key : @nodes.ObjectKey[T],
) -> XamlTypeDefinition {
  self.object_key = Some(key.id())
  self
}

///|
/// Register a base view: `view` gives, for an object of this type wrapped with `key`, its part that
/// a base type's operations registered with `base_key` work on, the same instance each time. An
/// inherited setter, getter, save reader, add operation, enumerator, store or callback registered
/// with `base_key` then runs on objects of this type through the view (design D8). Views compose
/// along the base chain: a type may register a view to its direct base type's key, whose own views
/// lead further.
pub fn[D, B] XamlTypeDefinition::base_view(
  self : XamlTypeDefinition,
  key : @nodes.ObjectKey[D],
  base_key : @nodes.ObjectKey[B],
  view : (D) -> B,
) -> XamlTypeDefinition {
  self.base_views.push({
    from_key: key.id(),
    to_key: base_key.id(),
    adapt: handle => {
      key.unwrap(handle).map(d => base_key.wrap(handle.type_name(), view(d)))
    },
  })
  self
}

///|
/// Register the begin and end initialization callbacks of the type, which derived types inherit, as
/// .NET `ISupportInitialize` (design D25).
pub fn XamlTypeDefinition::initialization(
  self : XamlTypeDefinition,
  begin~ : InitializationCallback,
  end~ : InitializationCallback,
) -> XamlTypeDefinition {
  self.begin_init = Some(begin)
  self.end_init = Some(end)
  self
}

///|
/// The id of the key that wraps objects of the type, its own or its nearest base type's.
pub fn XamlType::object_key_id(self : XamlType) -> Int32? {
  self.object_key
}

///|
/// Whether `key` is the key that wraps objects of the type.
pub fn[T] XamlType::has_object_key(
  self : XamlType,
  key : @nodes.ObjectKey[T],
) -> Bool {
  self.object_key == Some(key.id())
}

///|
/// Whether `handle` was wrapped with the key of the type.
pub fn XamlType::is_keyed_instance(
  self : XamlType,
  handle : @nodes.XamlObject,
) -> Bool {
  self.object_key == Some(handle.key_id())
}

///|
/// The begin initialization callback, declared or inherited, adapted to the type's key.
pub fn XamlType::begin_init(self : XamlType) -> InitializationCallback? {
  self.begin_init
}

///|
/// The end initialization callback, declared or inherited, adapted to the type's key.
pub fn XamlType::end_init(self : XamlType) -> InitializationCallback? {
  self.end_init
}

///|
/// Whether `value` is an instance of `target`: its runtime type, along its base chain, is `target`,
/// or `target` is `x:Object` (F10).
pub fn SchemaContext::is_instance_of(
  self : SchemaContext,
  value : @nodes.XamlValue,
  target : @nodes.XamlTypeName,
) -> Bool {
  match value_type_name(value) {
    Some(t) => target == object_type || self.is_assignable(t, target)
    None => target == object_type && value is List(_)
  }
}

///|
/// How a type reaches the key of a base type's operations.
priv enum Reach {
  /// The same key, or a key that is not registered: the operation runs as it is.
  Same
  /// Through composed base views.
  Via((@nodes.XamlObject) -> @nodes.XamlObject)
  /// No chain of base views leads to the key.
  Unreachable
}

///|
/// The key of each link of a base chain: its own, else the nearest base type's.
fn effective_keys(definitions : Array[XamlTypeDefinition]) -> Array[Int32?] {
  let keys : Array[Int32?] = Array::make(definitions.length(), None)
  let mut inherited : Int32? = None
  for i = definitions.length() - 1; i >= 0; i = i - 1 {
    if definitions[i].object_key is Some(key) {
      inherited = Some(key)
    }
    keys[i] = inherited
  }
  keys
}

///|
/// How the first type of the chain reaches the key of link `index`, through the base views that the
/// types between them register.
fn reach(
  definitions : Array[XamlTypeDefinition],
  keys : Array[Int32?],
  index : Int32,
) -> Reach {
  guard keys[0] is Some(from) && keys[index] is Some(to) && from != to else {
    return Same
  }
  // Breadth-first over the views of the types below `index`, from `from` to `to`.
  let edges : Array[BaseView] = []
  for i in 0.. {
        let mut current = handle
        for view in path {
          if current.key_id() == view.from_key {
            if (view.adapt)(current) is Some(adapted) {
              current = adapted
            }
          }
        }
        current
      })
    }
    for edge in edges {
      if edge.from_key == key && !paths.contains(edge.to_key) {
        let path = paths[key].copy()
        path.push(edge)
        paths[edge.to_key] = path
        pending.push(edge.to_key)
      }
    }
  }
  Unreachable
}

///|
/// `member` with its instance operations running through `adapt`.
fn XamlMember::through(
  self : XamlMember,
  adapt : (@nodes.XamlObject) -> @nodes.XamlObject,
) -> XamlMember {
  {
    ..self,
    setter: self.setter.map(f => (target, value) => f(adapt(target), value)),
    getter: self.getter.map(f => target => f(adapt(target))),
    save_reader: self.save_reader.map(f => target => f(adapt(target))),
    should_serialize: self.should_serialize.map(f => target => f(adapt(target))),
  }
}

///|
/// Whether a member has operations on the declaring type's instance, which need its key. Those of a dependency property take every
/// object with a dependency object.
fn XamlMember::has_instance_operations(self : XamlMember) -> Bool {
  self.kind is Property &&
  self.dependency_property is None &&
  (
    self.setter is Some(_) ||
    self.getter is Some(_) ||
    self.save_reader is Some(_) ||
    self.should_serialize is Some(_)
  )
}

///|
/// The nearest registration along a base chain that `pick` finds, with its link index.
fn[T] nearest(
  definitions : Array[XamlTypeDefinition],
  pick : (XamlTypeDefinition) -> T?,
) -> (T, Int32)? {
  for i, d in definitions {
    if pick(d) is Some(found) {
      return Some((found, i))
    }
  }
  None
}