// XAML types whose objects are or have dependency objects, and conversions to `AnyValue`.

///|
/// Gives the dependency object of a XAML object, or `None` when it has none.
pub type DependencyLink = (@nodes.XamlObject) -> @dependency.DependencyObject?

///|
/// Converts a value of a XAML type to an `AnyValue`. It raises an error for a value that it does not take.
pub type AnyValueConverter = (@nodes.XamlValue) -> @dependency.AnyValue raise

///|
/// The key of XAML objects that are dependency objects, such as those of `XamlTypeDefinition::dependency_objects`.
pub let dependency_object_key : @nodes.ObjectKey[@dependency.DependencyObject] = @nodes.ObjectKey::new(hash=object => {
    Hash::hash(object)
  },
)

///|
/// The dependency object in a value that `dependency_object_key` wrapped.
pub fn as_dependency_object(
  value : @nodes.XamlValue,
) -> @dependency.DependencyObject? {
  match value {
    Object(handle) => dependency_object_key.unwrap(handle)
    _ => None
  }
}

///|
/// Name the owner type that the XAML type stands for.
///
/// `object` gives the dependency object of an object of the type. Without it the type uses the function of its nearest base type
/// that has one. A type with neither, such as the static class `TextOptions`, has no objects with dependency properties and only
/// gives its name to attached ones.
///
/// `dependency_objects` does this for a type whose objects are dependency objects.
pub fn XamlTypeDefinition::dependency_owner(
  self : XamlTypeDefinition,
  owner : @dependency.OwnerType,
  object? : DependencyLink,
) -> XamlTypeDefinition {
  self.dependency_owners.push((owner, object))
  self
}

///|
/// Make the objects of the type dependency objects of the type `owner`, which `create` makes. Without `create` the type has no
/// constructor of its own.
///
/// A control that keeps more than its dependency object gives itself to it with `set_host`, and other members of the type find
/// it there. Each XAML type of such objects needs an owner type of its own, because a dependency object does not know more.
pub fn XamlTypeDefinition::dependency_objects(
  self : XamlTypeDefinition,
  owner : @dependency.OwnerType,
  create? : () -> @dependency.DependencyObject raise,
) -> XamlTypeDefinition {
  if create is Some(create) {
    self.constructors.push({
      factory_method: None,
      parameters: [],
      invoke: name => {
        (_, _) => Object(dependency_object_key.wrap(name, create()))
      },
      positional: true,
    })
  }
  self
  .object_key(dependency_object_key)
  .dependency_owner(owner, object=handle => dependency_object_key.unwrap(handle))
}

///|
/// Register the conversion of values of the type to `AnyValue`, for code such as a property path that has no property with a
/// type. Derived types inherit it.
pub fn XamlTypeDefinition::any_value_converter(
  self : XamlTypeDefinition,
  convert : AnyValueConverter,
) -> XamlTypeDefinition {
  self.any_value_converter = Some(convert)
  self
}

///|
/// The owner type that the type itself names.
pub fn XamlType::declared_dependency_owner(
  self : XamlType,
) -> @dependency.OwnerType? {
  self.declared_dependency_owner
}

///|
/// The owner type that the type or its nearest base type with one names.
pub fn XamlType::dependency_owner(self : XamlType) -> @dependency.OwnerType? {
  self.dependency_owner
}

///|
/// The dependency object of `object`, an object of the type.
pub fn XamlType::dependency_object(
  self : XamlType,
  object : @nodes.XamlObject,
) -> @dependency.DependencyObject? {
  self.dependency_link.bind(link => link(object))
}

///|
/// The conversion of values of the type to `AnyValue`: its own, else that of its nearest base type other than `x:Object`.
pub fn XamlType::any_value_converter(self : XamlType) -> AnyValueConverter? {
  self.any_value_converter
}

///|
/// The type that stands for `owner` in a document: the first one in the order of registration that names it itself.
pub fn SchemaContext::xaml_type_for_owner(
  self : SchemaContext,
  owner : @dependency.OwnerType,
) -> XamlType? {
  self.dependency_types.owners.get(owner).bind(name => self.get_type(name))
}

///|
/// The XAML object of `object`, for example to save it. The XAML type that stands for the owner type of the object registers
/// `dependency_objects`.
pub fn SchemaContext::xaml_object(
  self : SchemaContext,
  object : @dependency.DependencyObject,
) -> @nodes.XamlObject raise ValueError {
  self.dependency_types.xaml_object(object)
}

///|
/// What the functions that a schema context builds look up in the types of the context. They have this table and not the
/// context, which has them, so that native and wasm can free both.
priv struct DependencyTypes {
  /// `SchemaContext::index`.
  index : Map[TypeKey, TypeKey]
  /// The function of each linked type, adapted to its object key.
  links : Map[TypeKey, DependencyLink]
  /// The conversion of each type that has one, without that of `x:Object`.
  converters : Map[TypeKey, AnyValueConverter]
  /// The type that stands for each owner type.
  owners : Map[@dependency.OwnerType, @nodes.XamlTypeName]
  /// The attached member with which saving writes each attached property, and how to read its local value.
  attached : Map[@dependency.PropertyInfo, (@nodes.XamlMemberName, LocalReader)]
  /// The types and names of the attached members that are dependency properties, inherited ones too.
  attached_names : Set[(TypeKey, String)]
}

///|
fn DependencyTypes::new(index : Map[TypeKey, TypeKey]) -> DependencyTypes {
  {
    index,
    links: Map([]),
    converters: Map([]),
    owners: Map([]),
    attached: Map([]),
    attached_names: Set([]),
  }
}

///|
/// What `table` has for the registered type `name`.
fn[T] DependencyTypes::find(
  self : DependencyTypes,
  table : Map[TypeKey, T],
  name : @nodes.XamlTypeName,
) -> T? {
  self.index
  .get((language_alias(name.namespace_uri), name.name, name.arity()))
  .bind(key => table.get(key))
}

///|
/// The dependency object of `handle`, by its runtime type.
fn DependencyTypes::dependency_object(
  self : DependencyTypes,
  handle : @nodes.XamlObject,
) -> @dependency.DependencyObject raise ValueError {
  let name = handle.type_name()
  guard self.find(self.links, name) is Some(link) else {
    raise ValueError("objects of \{name} have no dependency object")
  }
  guard link(handle) is Some(object) else {
    raise ValueError("this object of \{name} has no dependency object")
  }
  object
}

///|
fn DependencyTypes::xaml_object(
  self : DependencyTypes,
  object : @dependency.DependencyObject,
) -> @nodes.XamlObject raise ValueError {
  let owner = object.owner_type()
  guard self.owners.get(owner) is Some(name) else {
    raise ValueError("no XAML type stands for the owner type `\{owner}`")
  }
  let handle = dependency_object_key.wrap(name, object)
  guard self.find(self.links, name) is Some(link) &&
    link(handle) == Some(object) else {
    raise ValueError(
      "a `\{owner}` object is no XAML object, because \{name} does not register `dependency_objects`",
    )
  }
  handle
}

///|
/// The conversion of `x:Object`: that of the runtime type of the value, or else the dependency object of a linked type, or else
/// the object itself.
fn DependencyTypes::any_value(
  self : DependencyTypes,
  value : @nodes.XamlValue,
) -> @dependency.AnyValue raise {
  if value is Null {
    return null_value_key.wrap(())
  }
  guard value_type_name(value) is Some(name) else {
    raise not_taken(object_type, value)
  }
  match (self.find(self.converters, name), value) {
    (Some(convert), _) => convert(value)
    (None, Object(handle)) =>
      if self.find(self.links, name) is Some(_) {
        @dependency.object_key.wrap(self.dependency_object(handle))
      } else {
        xaml_object_key.wrap(handle)
      }
    (None, _) => raise not_taken(object_type, value)
  }
}

///|
/// The conversion of values of the XAML type to `AnyValue`s of `key`, for a conversion that looks up no types.
fn[T] PropertyConversion::any_value_converter(
  self : PropertyConversion[T],
  key : @dependency.ValueKey[T],
) -> (String, AnyValueConverter) {
  let types = DependencyTypes::new(Map([]))
  let convert = value => key.wrap((self.from_xaml)(types, value))
  (self.value_type.name, convert)
}

///|
/// The conversions to `AnyValue` of the types of the language other than `x:Object`, by the names of the types.
fn primitive_any_values() -> Map[String, AnyValueConverter] {
  Map([
    bool_conversion.any_value_converter(@dependency.bool_key),
    byte_conversion.any_value_converter(@dependency.byte_key),
    int16_conversion.any_value_converter(@dependency.int16_key),
    int_conversion.any_value_converter(@dependency.int_key),
    int64_conversion.any_value_converter(@dependency.int64_key),
    float_conversion.any_value_converter(@dependency.float_key),
    double_conversion.any_value_converter(@dependency.double_key),
    char_conversion.any_value_converter(@dependency.char_key),
    string_conversion.any_value_converter(@dependency.string_key),
    decimal_conversion.any_value_converter(decimal_value_key),
    time_span_conversion.any_value_converter(time_span_value_key),
    uri_conversion.any_value_converter(uri_value_key),
  ])
}