///|
/// A handler in the list of an element or of a type.
priv struct Handler {
  event : RoutedEventInfo
  token : @dependency.HandlerToken
  handled_events_too : Bool
  run : (@dependency.DependencyObject, RoutingArgs) -> Unit raise
}

///|
/// The handlers of an element in the order in which they were added. An element without handlers has no list.
let handlers_key : @dependency.ValueKey[Array[Handler]] = @dependency.ValueKey::by_identity(
  "Handlers",
)

///|
/// `handler` as a handler that does not know the type of the data.
fn[A] RoutedEvent::untyped(
  self : RoutedEvent[A],
  handler : (@dependency.DependencyObject, RoutedEventArgs[A]) -> Unit raise,
) -> (@dependency.DependencyObject, RoutingArgs) -> Unit raise {
  let key = self.key
  (sender, routing) => {
    guard routing.event is Some((_, data)) && key.unwrap(data) is Some(data) else {
      abort("the arguments of a raise have data of another key")
    }
    handler(sender, { data, routing, })
  }
}

///|
/// Fail when `object` is no element, or one of another registry.
fn RoutedEventInfo::check_element(
  self : RoutedEventInfo,
  object : @dependency.DependencyObject,
) -> Unit raise @dependency.DependencyError {
  let owner = object.owner_type()
  if !owner.is_element() {
    raise InvalidEvent(
      "`\{self}` cannot be used on a `\{owner}` object, because `\{owner}` is not an element type",
    )
  }
  if object.registry_id() != self.registry_id {
    raise RegistryMismatch(
      "`\{self}` of \{self.registry_id} cannot be used on a `\{owner}` object of \{object.registry_id()}",
    )
  }
}

///|
/// Run `handler` on `element` for each raise of `event` whose route has the element. It gets `element` and the arguments of
/// the raise.
///
/// The event can be one of any type, also when the type of `element` has nothing to do with it. So a panel hears of the clicks
/// of its buttons. Handlers run in the order in which they were added, and one that is added twice runs twice.
///
/// Without `handled_events_too` the handler does not run when another one has handled the event. An error of a handler ends the
/// raise and reaches the code that made it.
pub fn[A] add_handler(
  element : @dependency.DependencyObject,
  event : RoutedEvent[A],
  handler : (@dependency.DependencyObject, RoutedEventArgs[A]) -> Unit raise,
  handled_events_too~ : Bool = false,
) -> @dependency.HandlerToken raise @dependency.DependencyError {
  add_routing_handler(
    element,
    event.info,
    event.untyped(handler),
    handled_events_too~,
  )
}

///|
/// As `add_handler`, for a handler that does not need the data and so can be one of events with data of different types.
pub fn add_routing_handler(
  element : @dependency.DependencyObject,
  event : RoutedEventInfo,
  handler : (@dependency.DependencyObject, RoutingArgs) -> Unit raise,
  handled_events_too~ : Bool = false,
) -> @dependency.HandlerToken raise @dependency.DependencyError {
  event.check_element(element)
  let token = @dependency.HandlerToken::new()
  let added = { event, token, handled_events_too, run: handler, }
  match element.extension(handlers_key) {
    Some(handlers) => handlers.push(added)
    None => element.set_extension(handlers_key, [added])
  }
  token
}

///|
/// Remove the handler for which `add_handler` or `add_routing_handler` returned `token` for this element. Returns false when
/// the element has no such handler.
pub fn remove_handler(
  element : @dependency.DependencyObject,
  token : @dependency.HandlerToken,
) -> Bool {
  guard element.extension(handlers_key) is Some(handlers) else { return false }
  // A new list, because `Array::remove` leaves the handler in the memory of the old one.
  let others = handlers.filter(handler => handler.token != token)
  if others.length() == handlers.length() {
    return false
  }
  if others.is_empty() {
    element.remove_extension(handlers_key)
  } else {
    element.set_extension(handlers_key, others)
  }
  true
}

///|
/// Remove all handlers of `element`, also those that a XAML document has added, for which there are no tokens.
pub fn release_handlers(element : @dependency.DependencyObject) -> Unit {
  element.remove_extension(handlers_key)
}