///|
/// On which elements the handlers of an event run. An event has exactly one strategy, as in WPF.
#derive(Eq, Hash, Debug)
pub(all) enum RoutingStrategy {
  /// On the element that raises the event, and then on its ancestors up to the root.
  Bubble
  /// The route of `Bubble` in the opposite direction. The names of such events start with `Preview` by convention.
  Tunnel
  /// Only on the element that raises the event.
  Direct
}

///|
/// A routed event without the type of its data.
///
/// All handles of one event are equal, also one that `lookup_routed_event` gives.
pub struct RoutedEventInfo {
  priv registry_id : @dependency.RegistryId
  /// The position in the order of registration.
  priv index : Int32
  priv name : String
  priv strategy : RoutingStrategy
  priv owner_type : @dependency.OwnerType
  priv args_key_id : @dependency.ValueKeyId
}

///|
pub impl Eq for RoutedEventInfo with fn equal(self, other) {
  self.index == other.index && self.registry_id == other.registry_id
}

///|
pub impl Hash for RoutedEventInfo with fn hash_combine(self, hasher) {
  hasher.combine(self.registry_id)
  hasher.combine_int(self.index)
}

///|
/// The event as `Owner.Name`.
pub impl Show for RoutedEventInfo with fn output(self, logger) {
  logger.write_string("\{self.owner_type}.\{self.name}")
}

///|
pub extend RoutedEventInfo with Show::{to_string}

///|
pub impl Debug for RoutedEventInfo with fn to_repr(self) {
  @debug.Repr::literal("\{self}")
}

///|
pub fn RoutedEventInfo::name(self : RoutedEventInfo) -> String {
  self.name
}

///|
pub fn RoutedEventInfo::strategy(self : RoutedEventInfo) -> RoutingStrategy {
  self.strategy
}

///|
/// The type on which the event was registered, not one that `add_owner` added.
pub fn RoutedEventInfo::owner_type(
  self : RoutedEventInfo,
) -> @dependency.OwnerType {
  self.owner_type
}

///|
pub fn RoutedEventInfo::registry_id(
  self : RoutedEventInfo,
) -> @dependency.RegistryId {
  self.registry_id
}

///|
/// The identity of the key that stands for the type of the data.
pub fn RoutedEventInfo::args_key_id(
  self : RoutedEventInfo,
) -> @dependency.ValueKeyId {
  self.args_key_id
}

///|
/// The event with the type of its data, which `key` stands for. It is an error when the event was registered with another
/// key.
pub fn[A] RoutedEventInfo::typed(
  self : RoutedEventInfo,
  key : @dependency.ValueKey[A],
) -> RoutedEvent[A] raise @dependency.DependencyError {
  if key.id() != self.args_key_id {
    raise InvalidEvent(
      "`\{self}` has `\{self.args_key_id}` data, not `\{key.id()}` data",
    )
  }
  { info: self, key, }
}

///|
/// A routed event with data of type `A`.
pub struct RoutedEvent[A] {
  priv info : RoutedEventInfo
  priv key : @dependency.ValueKey[A]
}

///|
/// The event without the type of its data.
pub fn[A] RoutedEvent::info(self : RoutedEvent[A]) -> RoutedEventInfo {
  self.info
}

///|
/// What this package keeps in a registry. Nothing in it holds the registry.
priv struct EventTable {
  /// The events by the types that own them and by name. `add_owner` adds some too.
  events : Map[(@dependency.OwnerType, String), RoutedEventInfo]
  mut event_count : Int32
  /// The handlers of each type, in the order in which they were registered.
  mut class_handlers : Map[
    RoutedEventInfo,
    Map[@dependency.OwnerType, Array[Handler]],
  ]
}

///|
let event_table_key : @dependency.ValueKey[EventTable] = @dependency.ValueKey::by_identity(
  "EventTable",
)

///|
/// The table of `registry`, which gets one when it has none.
fn event_table(registry : @dependency.PropertyRegistry) -> EventTable {
  if registry.extension(event_table_key) is Some(table) {
    return table
  }
  let table = { events: Map([]), event_count: 0, class_handlers: Map([]), }
  registry.set_extension(event_table_key, table)
  table
}

///|
/// Register a routed event on `owner`.
///
/// `args_key` stands for the type of the data that a raise gives to the handlers. It is the `unit_key` of
/// `moonrockz/dependency-object` for an event without data.
///
/// An owner type can have one event with a name. A type that derives from it can use the name for another event. Events and
/// properties do not share their names.
pub fn[A] register_routed_event(
  name : String,
  strategy : RoutingStrategy,
  owner : @dependency.OwnerType,
  args_key : @dependency.ValueKey[A],
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> RoutedEvent[A] raise @dependency.DependencyError {
  registry.check_owner(owner)
  if name.is_empty() {
    raise InvalidRegistration("an event of `\{owner}` needs a name")
  }
  let table = event_table(registry)
  if table.events.contains((owner, name)) {
    raise InvalidRegistration(
      "the event `\{owner}.\{name}` is registered already",
    )
  }
  let info = {
    registry_id: registry.id(),
    index: table.event_count,
    name,
    strategy,
    owner_type: owner,
    args_key_id: args_key.id(),
  }
  table.event_count += 1
  table.events[(owner, name)] = info
  { info, key: args_key, }
}

///|
/// Fail when the event, `owner` and `registry` do not belong together.
fn RoutedEventInfo::check_owner(
  self : RoutedEventInfo,
  owner : @dependency.OwnerType,
  registry : @dependency.PropertyRegistry,
) -> Unit raise @dependency.DependencyError {
  let of_owner = owner.registry_id()
  let given = registry.id()
  if of_owner != self.registry_id || of_owner != given {
    raise RegistryMismatch(
      "`\{owner}`, `\{self}` and `registry~` have to belong to one registry, but belong to \{of_owner}, \{self.registry_id} and \{given}",
    )
  }
}

///|
/// Make the event one of `owner` too, so that `lookup_routed_event` finds it there by its name. Returns the same event.
///
/// When `owner` has another event with this name, this is no error, as in WPF, and the lookup goes on to find the other one.
pub fn[A] RoutedEvent::add_owner(
  self : RoutedEvent[A],
  owner : @dependency.OwnerType,
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> RoutedEvent[A] raise @dependency.DependencyError {
  let info = self.info
  info.check_owner(owner, registry)
  let events = event_table(registry).events
  if !events.contains((owner, info.name)) {
    events[(owner, info.name)] = info
  }
  self
}

///|
/// The event with the name `name` of `owner`, or else of the nearest type that it derives from.
pub fn lookup_routed_event(
  owner : @dependency.OwnerType,
  name : String,
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> RoutedEventInfo? raise @dependency.DependencyError {
  registry.check_owner(owner)
  guard registry.extension(event_table_key) is Some(table) else { return None }
  for next = Some(owner); next is Some(owner); next = owner.base_type() {
    if table.events.get((owner, name)) is Some(found) {
      return Some(found)
    }
  }
  None
}