///|
/// The logical children of an element that has some, as a list that goes through the elements themselves. So the cost of an
/// edit does not depend on their number, and nothing refers to an element that was removed.
priv struct Children {
  mut first : DependencyObject
  mut last : DependencyObject
  mut count : Int32
  /// How many walks go over the children now.
  mut walks : Int32
}

///|
/// How deep a walk goes below the element at which it starts, as `MAX_ELEMENTS_IN_ROUTE` in WPF.
let max_depth : Int32 = 4096

///|
/// The element that has this one as a logical child, or `None` when there is none.
pub fn DependencyObject::logical_parent(
  self : DependencyObject,
) -> DependencyObject? {
  self.parent
}

///|
/// The next element on the route of an event to the root. This is the logical parent.
pub fn DependencyObject::route_parent(
  self : DependencyObject,
) -> DependencyObject? {
  self.parent
}

///|
/// The logical children in their order. The result is a copy.
pub fn DependencyObject::logical_children(
  self : DependencyObject,
) -> Array[DependencyObject] {
  let found = []
  if self.children is Some(children) {
    for next = Some(children.first); next is Some(child); next = child.next {
      found.push(child)
    }
  }
  found
}

///|
/// Make `child` the last logical child. A control does this for an element that becomes a part of it. Nothing happens when
/// `child` is a logical child of this element already, or when its type is not an element type.
///
/// `child` and the elements below it then inherit values from their new ancestors and notify the changes. An error of a
/// callback or a handler reaches the caller, and `child` stays a logical child.
pub fn DependencyObject::add_logical_child(
  self : DependencyObject,
  child : DependencyObject,
) -> Unit raise {
  enter(() => "\{self.owner_type}.add_logical_child")
  defer leave()
  if self.check_link(child) {
    self.link(child, None)
  }
}

///|
/// Make `child` a logical child, as `add_logical_child` does, at the position `index`, which can be the number of logical
/// children.
pub fn DependencyObject::insert_logical_child(
  self : DependencyObject,
  index : Int32,
  child : DependencyObject,
) -> Unit raise {
  enter(() => "\{self.owner_type}.insert_logical_child")
  defer leave()
  let is_element = self.check_link(child)
  let count = match self.children {
    Some(children) => children.count
    None => 0
  }
  check_index(index, count + 1)
  guard is_element else { return }
  let mut before = None
  if index < count && self.children is Some(children) {
    before = Some(children.first)
    for _ in 0.. child.next)
    }
  }
  self.link(child, before)
}

///|
/// Make `child` an element without a logical parent. Nothing happens when it is not a logical child of this element. An
/// `ElementCollection` that has it keeps it.
///
/// `child` and the elements below it then lose the values of their former ancestors and notify the changes.
pub fn DependencyObject::remove_logical_child(
  self : DependencyObject,
  child : DependencyObject,
) -> Unit raise {
  enter(() => "\{self.owner_type}.remove_logical_child")
  defer leave()
  self.unlink(child)
}

///|
/// Fail when `index` is not one of `count` positions.
fn check_index(index : Int32, count : Int32) -> Unit raise DependencyError {
  if index < 0 || index >= count {
    raise InvalidTreeEdit(
      "the index \{index} is not one of the \{count} possible ones",
    )
  }
}

///|
/// Fail when the type is not an element type.
fn DependencyObject::check_parent(
  self : DependencyObject,
) -> Unit raise DependencyError {
  if !self.owner_type.element {
    raise InvalidTreeEdit(
      "a `\{self.owner_type}` object has no logical children, because `\{self.owner_type}` is not an element type",
    )
  }
}

///|
/// Fail while a walk goes over the logical children.
fn DependencyObject::check_not_walked(
  self : DependencyObject,
) -> Unit raise DependencyError {
  if self.children is Some({ walks, .. }) && walks > 0 {
    raise InvalidTreeEdit(
      "Cannot modify the logical children for this node at this time because a tree walk is in progress.",
    )
  }
}

///|
fn DependencyObject::check_same_registry(
  self : DependencyObject,
  child : DependencyObject,
) -> Unit raise DependencyError {
  if child.registry.id != self.registry.id {
    raise RegistryMismatch(
      "a `\{child.owner_type}` object cannot be a logical child of a `\{self.owner_type}` object of another registry",
    )
  }
}

///|
/// Fail when `child` cannot become a logical child. The checks, their order and their messages are those of
/// `AddLogicalChild` and `ChangeLogicalParent` in WPF, and then come the checks that only this module has. Returns false when
/// `child` is not an element, and so is ignored.
fn DependencyObject::check_link(
  self : DependencyObject,
  child : DependencyObject,
) -> Bool raise DependencyError {
  self.check_parent()
  self.check_not_walked()
  guard child.owner_type.element else { return false }
  if child.parent is Some(parent) && parent != self {
    raise InvalidTreeEdit(
      "Specified element is already the logical child of another element. Disconnect it first.",
    )
  }
  if child == self {
    raise InvalidTreeEdit("Element cannot be its own parent.")
  }
  self.check_same_registry(child)
  true
}

///|
/// Put `child`, for which `check_link` gave true, before the logical child `before` or else at the end, and evaluate what
/// its subtree inherits.
fn DependencyObject::link(
  self : DependencyObject,
  child : DependencyObject,
  before : DependencyObject?,
) -> Unit raise {
  guard child.parent is None else { return }
  child.parent = Some(self)
  match self.children {
    None =>
      self.children = Some({ first: child, last: child, count: 1, walks: 0, })
    Some(children) => {
      let previous = match before {
        Some(next) => next.previous
        None => Some(children.last)
      }
      child.previous = previous
      child.next = before
      match previous {
        Some(previous) => previous.next = Some(child)
        None => children.first = child
      }
      match before {
        Some(next) => next.previous = Some(child)
        None => children.last = child
      }
      children.count += 1
    }
  }
  child.inherit_subtree()
}

///|
/// Take `child` out of the logical children when it is one of them, and evaluate what its subtree inherits.
fn DependencyObject::unlink(
  self : DependencyObject,
  child : DependencyObject,
) -> Unit raise {
  self.check_not_walked()
  guard child.parent is Some(parent) &&
    parent == self &&
    self.children is Some(children) else {
    return
  }
  match (child.previous, child.next) {
    (None, None) => self.children = None
    (None, Some(next)) => {
      next.previous = None
      children.first = next
    }
    (Some(previous), None) => {
      previous.next = None
      children.last = previous
    }
    (Some(previous), Some(next)) => {
      previous.next = Some(next)
      next.previous = Some(previous)
    }
  }
  children.count -= 1
  child.parent = None
  child.previous = None
  child.next = None
  child.inherit_subtree()
}

///|
/// Make `new` the logical child in place of `old`, after the value of a property with logical content has changed. The steps
/// are those of `ContentControl.OnContentChanged` in WPF. Each makes its own checks, and what is done stays when one fails.
fn DependencyObject::change_content(
  self : DependencyObject,
  old : DependencyObject?,
  new : DependencyObject?,
) -> Unit raise {
  if old is Some(old) {
    self.unlink(old)
  }
  guard new is Some(new) else { return }
  if new.parent is Some(parent) {
    self.check_same_registry(new)
    parent.unlink(new)
  }
  if self.check_link(new) {
    self.link(new, None)
  }
}

///|
/// Call `visit` for the elements below this one, a parent before its children and these in their order. It is not called for
/// the elements below one for which it returns false.
///
/// The children of an element are read after the call for it. They cannot be changed until the walk has gone over them, so it
/// finds its way back through the parents and needs no stack.
fn DependencyObject::walk(
  self : DependencyObject,
  visit : (DependencyObject) -> Bool raise,
) -> Unit raise {
  let mut element = self
  let mut depth = 0
  let mut next = self.start_walk()
  defer {
    // An error can come from any depth.
    for _ in 0.. {
        if depth == max_depth {
          raise TreeLoop(
            "Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree.",
          )
        }
        next = child.next
        if visit(child) && child.start_walk() is Some(first) {
          element = child
          depth += 1
          next = Some(first)
        }
      }
      None if depth == 0 => break
      None => {
        element.end_walk()
        next = element.next
        element = element.parent.unwrap()
        depth -= 1
      }
    }
  }
}

///|
/// The first of the logical children, which cannot be changed from now on.
fn DependencyObject::start_walk(self : DependencyObject) -> DependencyObject? {
  guard self.children is Some(children) else { return None }
  children.walks += 1
  Some(children.first)
}

///|
fn DependencyObject::end_walk(self : DependencyObject) -> Unit {
  if self.children is Some(children) {
    children.walks -= 1
  }
}