///|
/// The elements of a control, such as the children of a panel. Each element that the collection gets becomes a logical child
/// of the owner, and each that it loses does not stay one.
///
/// An element that is not a child of the owner any more keeps its slot: this is so after `remove_logical_child` of the owner,
/// and when another control takes the element as its content.
pub struct ElementCollection {
  priv owner : DependencyObject
  priv mut slots : Array[DependencyObject]
  /// The elements in `slots`.
  priv elements : Set[DependencyObject]
}

///|
/// An empty collection of logical children of `owner`.
pub fn ElementCollection::new(
  owner : DependencyObject,
) -> ElementCollection raise DependencyError {
  owner.check_parent()
  { owner, slots: [], elements: Set([]), }
}

///|
pub fn ElementCollection::length(self : ElementCollection) -> Int32 {
  self.slots.length()
}

///|
/// The element at `index`, or `None` when there is no such index.
pub fn ElementCollection::get(
  self : ElementCollection,
  index : Int32,
) -> DependencyObject? {
  self.slots.get(index)
}

///|
/// The elements that the collection has now.
pub fn ElementCollection::iter(
  self : ElementCollection,
) -> Iter[DependencyObject] {
  self.slots.copy().iter()
}

///|
pub fn ElementCollection::contains(
  self : ElementCollection,
  element : DependencyObject,
) -> Bool {
  self.elements.contains(element)
}

///|
/// Put `element` at the end. It has no parent, or the owner is its parent already.
pub fn ElementCollection::add(
  self : ElementCollection,
  element : DependencyObject,
) -> Unit raise {
  self.insert(self.slots.length(), element)
}

///|
/// Put `element` at `index`, which can be the length. It has no parent, or the owner is its parent already.
///
/// An error of a callback or a handler that hears of a new inherited value reaches the caller, and the element stays in the
/// collection.
pub fn ElementCollection::insert(
  self : ElementCollection,
  index : Int32,
  element : DependencyObject,
) -> Unit raise {
  enter(() => "ElementCollection.insert")
  defer leave()
  check_index(index, self.slots.length() + 1)
  self.check_new(element)
  self.slots.insert(index, element)
  self.elements.insert(element)
  self.link_slot(index, element)
}

///|
/// Put `element` in the slot at `index`. The old element is unlinked first, while it has the slot. When that fails, it keeps
/// the slot. Nothing happens when `element` has this slot.
pub fn ElementCollection::replace(
  self : ElementCollection,
  index : Int32,
  element : DependencyObject,
) -> Unit raise {
  enter(() => "ElementCollection.replace")
  defer leave()
  check_index(index, self.slots.length())
  let old = self.slots[index]
  if old == element {
    return
  }
  self.check_new(element)
  self.owner.unlink(old)
  // A callback can have changed the collection.
  self.check_new(element)
  guard self.slots.get(index) is Some(found) && found == old else {
    raise InvalidTreeEdit(
      "the collection was changed at the index \{index} while its element was replaced",
    )
  }
  self.slots[index] = element
  self.elements.remove(old)
  self.elements.insert(element)
  self.link_slot(index, element)
}

///|
/// Remove `element`, and unlink it when the owner is its parent, also when the collection does not have it.
pub fn ElementCollection::remove(
  self : ElementCollection,
  element : DependencyObject,
) -> Unit raise {
  enter(() => "ElementCollection.remove")
  defer leave()
  if self.contains(element) && self.slots.search(element) is Some(index) {
    ignore(self.free_slot(index))
  }
  self.owner.unlink(element)
}

///|
/// Remove the element at `index`, and unlink it when the owner is its parent.
pub fn ElementCollection::remove_at(
  self : ElementCollection,
  index : Int32,
) -> Unit raise {
  enter(() => "ElementCollection.remove_at")
  defer leave()
  check_index(index, self.slots.length())
  self.owner.unlink(self.free_slot(index))
}

///|
/// Remove all elements, and then unlink one after the other. When that fails for one, the later ones stay logical children
/// of the owner.
pub fn ElementCollection::clear(self : ElementCollection) -> Unit raise {
  enter(() => "ElementCollection.clear")
  defer leave()
  let old = self.slots
  self.slots = []
  self.elements.clear()
  for element in old {
    self.owner.unlink(element)
  }
}

///|
/// Fail when `element` cannot get a slot.
fn ElementCollection::check_new(
  self : ElementCollection,
  element : DependencyObject,
) -> Unit raise DependencyError {
  if !self.owner.check_link(element) {
    raise InvalidTreeEdit(
      "a `\{element.owner_type}` object cannot be in an element collection, because `\{element.owner_type}` is not an element type",
    )
  }
  if self.contains(element) && self.slots.search(element) is Some(index) {
    raise InvalidTreeEdit(
      "\{object_key.text(element)} is in the collection already, at the index \{index}",
    )
  }
}

///|
/// Link the element at `index`. Its place among the logical children is that of its slot.
fn ElementCollection::link_slot(
  self : ElementCollection,
  index : Int32,
  element : DependencyObject,
) -> Unit raise {
  let mut before = None
  for i in (index + 1).. DependencyObject {
  let element = self.slots.remove(index)
  // The array still refers to its former last element, which native and wasm would not free then.
  self.slots.push(self.owner)
  ignore(self.slots.pop())
  self.elements.remove(element)
  element
}