// XAML members that are dependency properties.

///|
/// Whether saving writes the value of a dependency property of an object. It has no say for a value that is not local.
pub type ShouldSerializeProperty = (@dependency.DependencyObject) -> Bool raise

///|
/// Gives the local value of a dependency property of an object, or `None`.
type LocalReader = (DependencyTypes, @dependency.DependencyObject) -> @nodes.XamlValue? raise

///|
/// The dependency property of a member, with its operations on the values of XAML.
priv struct DependencyMember {
  property : @dependency.PropertyInfo
  set : (DependencyTypes, @dependency.DependencyObject, @nodes.XamlValue) -> Unit raise
  get : (DependencyTypes, @dependency.DependencyObject) -> @nodes.XamlValue raise
  read_local : LocalReader
  should_serialize : ShouldSerializeProperty?
}

///|
fn[T] PropertyConversion::dependency_member(
  self : PropertyConversion[T],
  property : @dependency.DependencyProperty[T],
  should_serialize : ShouldSerializeProperty?,
) -> DependencyMember {
  {
    property: property.info(),
    set: (types, object, value) => {
      object.set_value(property, (self.from_xaml)(types, value))
    },
    get: (types, object) => (self.to_xaml)(types, object.get_value(property)),
    read_local: (types, object) => {
      match object.read_local_value(property) {
        Some(value) => Some((self.to_xaml)(types, value))
        None => None
      }
    },
    should_serialize,
  }
}

///|
/// Add a member that is a dependency property of the objects of the type, as `conversion` converts its values. The type or a
/// base type of it has registered `dependency_objects` or `dependency_owner` with a function.
///
/// Loading sets the property, and a read-only property has no setter. Saving writes the local value, when there is one. The
/// other options are those of `add_member`, and the contents of a read-only collection are written unless `visibility` is
/// `Hidden`.
pub fn[T] XamlTypeDefinition::add_dependency_member(
  self : XamlTypeDefinition,
  name : String,
  property : @dependency.DependencyProperty[T],
  conversion : PropertyConversion[T],
  type_converter? : TypeConverter,
  value_serializer? : ValueSerializer,
  bracket_pairs~ : ArrayView[(Char, Char)] = [],
  should_serialize? : ShouldSerializeProperty,
  visibility? : SerializationVisibility,
  depends_on~ : ArrayView[String] = [],
  constructor_argument? : String,
) -> XamlTypeDefinition {
  ignore(
    self.add_member(
      name,
      value_type=conversion.value_type,
      nullable=conversion.nullable,
      type_converter?,
      value_serializer?,
      bracket_pairs~,
      visibility=visibility.unwrap_or(default_visibility(property)),
      depends_on~,
      constructor_argument?,
    ),
  )
  self.map_last_member(conversion.dependency_member(property, should_serialize))
}

///|
/// Add an attached member that is a dependency property, such as `Grid.Row`. It can be set on every object that has a dependency
/// object. The type itself names the owner type of the property, or one that the property was added to.
///
/// The options are those of `add_dependency_member`.
pub fn[T] XamlTypeDefinition::add_attached_dependency_member(
  self : XamlTypeDefinition,
  name : String,
  property : @dependency.DependencyProperty[T],
  conversion : PropertyConversion[T],
  type_converter? : TypeConverter,
  value_serializer? : ValueSerializer,
  bracket_pairs~ : ArrayView[(Char, Char)] = [],
  should_serialize? : ShouldSerializeProperty,
  visibility? : SerializationVisibility,
) -> XamlTypeDefinition {
  ignore(
    self.add_attached_member(
      name,
      value_type=conversion.value_type,
      nullable=conversion.nullable,
      type_converter?,
      value_serializer?,
      bracket_pairs~,
      visibility=visibility.unwrap_or(default_visibility(property)),
    ),
  )
  self.map_last_member(conversion.dependency_member(property, should_serialize))
}

///|
/// A read-only property can only be written as its contents, which needs the visibility `Content` (WPF `ElementMarkupObject`).
fn[T] default_visibility(
  property : @dependency.DependencyProperty[T],
) -> SerializationVisibility {
  if property.info().is_read_only() {
    Content
  } else {
    Visible
  }
}

///|
fn XamlTypeDefinition::map_last_member(
  self : XamlTypeDefinition,
  dependency : DependencyMember,
) -> XamlTypeDefinition {
  let last = self.members.length() - 1
  self.members[last] = { ..self.members[last], dependency: Some(dependency), }
  self
}

///|
/// The member with the operations of `dependency`. They find the dependency object by the type of the object that they get, so
/// no base view adapts it.
fn XamlMember::with_dependency(
  self : XamlMember,
  dependency : DependencyMember,
  types : DependencyTypes,
) -> XamlMember {
  let { property, set, get, read_local, should_serialize, } = dependency
  {
    ..self,
    dependency_property: Some(property),
    setter: if property.is_read_only() {
      None
    } else {
      Some((target, value) => set(types, types.dependency_object(target), value))
    },
    getter: Some(target => get(types, types.dependency_object(target))),
    save_reader: if self.kind is Attached {
      // The attached member store has the values.
      None
    } else {
      Some(target => read_local(types, types.dependency_object(target)))
    },
    should_serialize: should_serialize.map(check => {
      target => check(types.dependency_object(target))
    }),
  }
}

///|
/// Find the attached member with which saving writes each attached property: the first one whose type stands for the owner type of
/// the property, because WPF writes `OwnerType.Name` (`DependencyObjectPropertyDescriptor`). A read-only property without contents
/// is not written.
fn DependencyTypes::add_attached_members(
  self : DependencyTypes,
  records : Array[TypeRecord],
  types : Map[TypeKey, XamlType],
) -> Unit {
  let type_of = name => {
    self.index.get(definition_key(name)).bind(key => types.get(key))
  }
  for record in records {
    guard type_of(record.identity) is Some(owner) else { continue }
    let key = definition_key(owner.name)
    for name, found in owner.attached {
      if found.dependency_property is Some(_) {
        self.attached_names.insert((key, name))
      }
    }
    for entry in record.definition.members {
      guard entry is { kind: Attached, dependency: Some(dependency), .. } &&
        owner.declared_dependency_owner ==
        Some(dependency.property.owner_type()) &&
        !self.attached.contains(dependency.property) else {
        continue
      }
      let has_contents = entry.value_type.bind(type_of) is Some(type_) &&
        (type_.is_collection() || type_.is_dictionary())
      if !dependency.property.is_read_only() || has_contents {
        self.attached[dependency.property] = (
          Attached(owner=owner.name, name=entry.name),
          dependency.read_local,
        )
      }
    }
  }
}

///|
/// The attached members of `target` with their values: the local values of the attached properties other than those in `direct`, the
/// properties of members of its type, and the entries of the `registered` store that are no dependency properties.
fn DependencyTypes::attached_values(
  self : DependencyTypes,
  target : @nodes.XamlObject,
  direct : Set[@dependency.PropertyInfo],
  registered : AttachedMemberStore?,
) -> ReadOnlyArray[(@nodes.XamlMemberName, @nodes.XamlValue)] raise {
  let object = self.dependency_object(target)
  let values = []
  if registered is Some(store) {
    for entry in store(target) {
      let is_property = entry.0 is Attached(owner~, name~) &&
        self.index.get(definition_key(owner)) is Some(key) &&
        self.attached_names.contains((key, name))
      if !is_property {
        values.push(entry)
      }
    }
  }
  for entry in object.local_values() {
    guard !direct.contains(entry.0) &&
      self.attached.get(entry.0) is Some((name, read_local)) else {
      continue
    }
    let value = read_local(self, object) catch {
      error => raise ValueError("\{entry.0}: \{error_message(error)}")
    }
    if value is Some(value) {
      values.push((name, value))
    }
  }
  ReadOnlyArray::from_array(values)
}

///|
/// The dependency object behind an object that `xaml_object` gives again, so that a place which keeps only the dependency object
/// does not lose the type.
fn DependencyTypes::plain_dependency_object(
  self : DependencyTypes,
  value : @nodes.XamlValue,
) -> @dependency.DependencyObject raise ValueError {
  guard value is Object(handle) else {
    raise ValueError("\{input_text(value)} is no dependency object")
  }
  let object = self.dependency_object(handle)
  let name = self.xaml_object(object).type_name()
  if canonical_in(self.index, handle.type_name()) !=
    canonical_in(self.index, name) {
    raise ValueError(
      "this object of \{handle.type_name()} would become one of \{name}, which stands for its owner type `\{object.owner_type()}`",
    )
  }
  object
}

///|
/// The conversion for properties whose values are the dependency objects of the XAML type `value_type`. These register
/// `dependency_objects`.
pub fn PropertyConversion::dependency_object(
  value_type : @nodes.XamlTypeName,
) -> PropertyConversion[@dependency.DependencyObject] {
  {
    value_type,
    nullable: false,
    from_xaml: (types, value) => types.plain_dependency_object(value),
    to_xaml: (types, object) => Object(types.xaml_object(object)),
  }
}

///|
/// `ElementCollection` in `urn:moonrockz:xaml`, the type of the collections that `element_collection_value` gives.
pub let element_collection_type : @nodes.XamlTypeName = @nodes.XamlTypeName::new(
  moonrockz_namespace, "ElementCollection",
)

///|
let element_collection_key : @nodes.ObjectKey[@dependency.ElementCollection] = @nodes.ObjectKey::new()

///|
/// The XAML object of a collection of elements, such as the children of a panel, for the getter of a member of the type
/// `element_collection_type`. Its items are objects of types with `dependency_objects`.
pub fn element_collection_value(
  collection : @dependency.ElementCollection,
) -> @nodes.XamlValue {
  Object(element_collection_key.wrap(element_collection_type, collection))
}

///|
fn element_collection_definition(types : DependencyTypes) -> XamlTypeDefinition {
  let collection_of = target => {
    state_of(element_collection_key, target, "ElementCollection")
  }
  XamlTypeDefinition::new(moonrockz_namespace, "ElementCollection")
  .object_key(element_collection_key)
  .collection((target, item) => {
    collection_of(target).add(types.plain_dependency_object(item))
  })
  .item_enumerator(target => {
    let items : Array[@nodes.XamlValue] = []
    for element in collection_of(target).iter() {
      items.push(Object(types.xaml_object(element)))
    }
    ReadOnlyArray::from_array(items)
  })
}