// Registrations that saving reads instead of reflection (design D3, D20 to D24).

///|
/// Whether saving writes a member, as .NET `DesignerSerializationVisibilityAttribute` decides.
#derive(Eq, Hash, Debug)
pub(all) enum SerializationVisibility {
  /// Written as its value: the default.
  Visible
  /// Never written.
  Hidden
  /// Its contents are written even when the member is read-only.
  Content
}

///|
/// Reads the value that saving compares with the default and writes, separately from the getter
/// that loading uses; `None` means unset, so the member is not written (design D21).
pub type SaveReader = (@nodes.XamlObject) -> @nodes.XamlValue? raise

///|
/// Decides whether saving writes a member of an object, as a `ShouldSerialize` method does.
pub type ShouldSerialize = (@nodes.XamlObject) -> Bool raise

///|
/// The items of a collection object, in order, for saving.
pub type ItemEnumerator = (@nodes.XamlObject) -> ReadOnlyArray[@nodes.XamlValue] raise

///|
/// The keyed entries of a dictionary object, in order, for saving.
pub type EntryEnumerator = (@nodes.XamlObject) -> ReadOnlyArray[
  (@nodes.XamlValue, @nodes.XamlValue),
] raise

///|
/// How to construct an object again, as .NET `InstanceDescriptor` gives it: a constructor, or a
/// factory method by the type that registers it and its name, with its arguments, and whether the
/// arguments describe the object completely, so that no member needs writing.
#derive(Eq, Debug)
pub(all) struct InstanceDescriptor {
  factory_method : (@nodes.XamlTypeName, String)?
  arguments : ReadOnlyArray[@nodes.XamlValue]
  complete : Bool
}

///|
/// Gives the instance descriptor of an object.
pub type InstanceDescriber = (@nodes.XamlObject) -> InstanceDescriptor raise

///|
/// Lists the attached members set on an object with their values, as .NET
/// `IAttachedPropertyStore` and `AttachablePropertyServices` do.
pub type AttachedMemberStore = (@nodes.XamlObject) -> ReadOnlyArray[
  (@nodes.XamlMemberName, @nodes.XamlValue),
] raise

///|
/// Register an enumerator of the items of the collection type, which saving needs. The type or a
/// base type must register an add operation.
pub fn XamlTypeDefinition::item_enumerator(
  self : XamlTypeDefinition,
  enumerate : ItemEnumerator,
) -> XamlTypeDefinition {
  self.item_enumerator = Some(enumerate)
  self
}

///|
/// Register an enumerator of the entries of the dictionary type, which saving needs. The type or a
/// base type must register an add operation.
pub fn XamlTypeDefinition::entry_enumerator(
  self : XamlTypeDefinition,
  enumerate : EntryEnumerator,
) -> XamlTypeDefinition {
  self.entry_enumerator = Some(enumerate)
  self
}

///|
/// Register the instance descriptor of the type, which derived types inherit.
pub fn XamlTypeDefinition::instance_descriptor(
  self : XamlTypeDefinition,
  describe : InstanceDescriber,
) -> XamlTypeDefinition {
  self.instance_descriptor = Some(describe)
  self
}

///|
/// Register the attached member store of the type, which derived types inherit.
pub fn XamlTypeDefinition::attached_member_store(
  self : XamlTypeDefinition,
  store : AttachedMemberStore,
) -> XamlTypeDefinition {
  self.attached_store = Some(store)
  self
}

///|
/// The enumerator of the items of a collection, declared or inherited.
pub fn XamlType::item_enumerator(self : XamlType) -> ItemEnumerator? {
  self.item_enumerator
}

///|
/// The enumerator of the entries of a dictionary, declared or inherited.
pub fn XamlType::entry_enumerator(self : XamlType) -> EntryEnumerator? {
  self.entry_enumerator
}

///|
/// The instance descriptor of the type, declared or inherited.
pub fn XamlType::instance_descriptor(self : XamlType) -> InstanceDescriber? {
  self.instance_descriptor
}

///|
/// The attached member store of the type, declared or inherited.
pub fn XamlType::attached_member_store(self : XamlType) -> AttachedMemberStore? {
  self.attached_store
}

///|
/// The full CLR-style name `N.Name` of a type that registers a CLR-style namespace, which `x:Class`
/// is compared with. A generic type has none.
pub fn XamlType::full_name(self : XamlType) -> String? {
  guard self.clr_namespace is Some(namespace_) &&
    self.type_parameters.is_empty() else {
    return None
  }
  Some("\{namespace_}.\{self.name.name}")
}

///|
/// The save reader of the member, inherited with it (design D21).
pub fn XamlMember::save_reader(self : XamlMember) -> SaveReader? {
  self.save_reader
}

///|
/// The should-serialize check of the member.
pub fn XamlMember::should_serialize(self : XamlMember) -> ShouldSerialize? {
  self.should_serialize
}

///|
/// The constructor or factory method that `descriptor` gives for an object of `target`: the most
/// specific one that takes the arguments as they are, without widening. The target of the
/// descriptor, the number of its arguments and the type of each argument have their own errors, as
/// in System.Xaml `AddFactoryMethodAndValidateArguments` (design D23).
pub fn SchemaContext::descriptor_constructor(
  self : SchemaContext,
  target : XamlType,
  descriptor : InstanceDescriptor,
) -> XamlConstructor raise ArgumentsError {
  let { factory_method, arguments, .. } = descriptor
  let type_name = target.name
  let candidates = match factory_method {
    Some((owner, name)) =>
      self
      .get_type(owner)
      .map(owner => owner.factory_methods(name))
      .unwrap_or([])
    None => target.constructors()
  }
  if candidates.is_empty() {
    raise InvalidDescriptor(type_name~, factory_method~)
  }
  let candidates = candidates.filter(c => c.arity() == arguments.length())
  let applicable = []
  let mut misfit : (@nodes.XamlValue, @nodes.XamlTypeName)? = None
  for candidate in candidates {
    for i, parameter in candidate.parameters {
      if self.fit(parameter, arguments[i]) != Some(false) {
        if misfit is None {
          misfit = Some((arguments[i], parameter.type_name))
        }
        break
      }
    } nobreak {
      applicable.push(candidate)
    }
  }
  if applicable.is_empty() {
    guard misfit is Some((argument, parameter_type)) else {
      raise WrongDescriptorArgumentCount(
        type_name~,
        factory_method~,
        count=arguments.length(),
      )
    }
    raise WrongDescriptorArgumentType(
      type_name~,
      factory_method~,
      argument_type=value_type_name(argument),
      parameter_type~,
    )
  }
  let best = self.most_specific(
    target,
    applicable,
    arguments[:],
    factory_method.map(f => f.1),
  )
  applicable[best]
}