///|
/// The identity of a registry. It does not hold the registry, so that a record in an extension table can keep it.
#derive(Eq, Hash)
pub struct RegistryId {
  priv number : Int32
}

///|
pub impl Show for RegistryId with fn output(self, logger) {
  logger.write_string("registry \{self.number}")
}

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

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

///|
/// Owner types, dependency properties and the tables of other packages.
///
/// Every function that registers or looks up something uses the default registry of the process, unless it gets another
/// one with `registry~`. A type, a property or an object of one registry cannot be used with those of another.
///
/// Nothing in a registry holds the registry: types and properties have only its `id`. Records in an extension table have
/// to do the same, so that every target frees a registry that a program drops.
pub struct PropertyRegistry {
  priv id : RegistryId
  priv type_names : Set[String]
  priv properties : Map[(OwnerType, String), PropertyInfo]
  priv mut property_count : Int32
  priv extensions : Array[AnyValue]
}

///|
let last_registry : Ref[Int32] = Ref(0)

///|
/// A new registry that shares nothing with other registries.
pub fn PropertyRegistry::new() -> PropertyRegistry {
  last_registry.val += 1
  {
    id: { number: last_registry.val, },
    type_names: Set([]),
    properties: Map([]),
    property_count: 0,
    extensions: [],
  }
}

///|
let default_registry : PropertyRegistry = PropertyRegistry::new()

///|
/// The registry of the process.
pub fn PropertyRegistry::default() -> PropertyRegistry {
  default_registry
}

///|
pub fn PropertyRegistry::id(self : PropertyRegistry) -> RegistryId {
  self.id
}

///|
/// The table that a package keeps in the registry under its own key.
pub fn[T] PropertyRegistry::extension(
  self : PropertyRegistry,
  key : ValueKey[T],
) -> T? {
  extension_of(self.extensions, key)
}

///|
/// Keep `value` in the registry under `key`, in the place of the value that was there.
pub fn[T] PropertyRegistry::set_extension(
  self : PropertyRegistry,
  key : ValueKey[T],
  value : T,
) -> Unit {
  set_extension_of(self.extensions, key, value)
}

///|
/// Fail when `owner` is a type of another registry. Functions of other packages that get a registry and a type call it.
pub fn PropertyRegistry::check_owner(
  self : PropertyRegistry,
  owner : OwnerType,
) -> Unit raise DependencyError {
  if owner.registry_id != self.id {
    raise RegistryMismatch(
      "`\{owner}` belongs to another registry, which has to be given as `registry~`",
    )
  }
}

///|
/// Fail when `owner` has a property with the name `name`, which can also be one that was added to it.
fn PropertyRegistry::check_name(
  self : PropertyRegistry,
  owner : OwnerType,
  name : String,
) -> Unit raise DependencyError {
  if self.properties.contains((owner, name)) {
    raise InvalidRegistration("`\{owner}.\{name}` is registered already")
  }
}

///|
/// A type of dependency objects. It owns the names of properties, and properties can have metadata for it.
pub struct OwnerType {
  priv registry_id : RegistryId
  priv number : Int32
  priv name : String
  priv base : OwnerType?
  priv element : Bool
}

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

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

///|
/// The name of the type.
pub impl Show for OwnerType with fn output(self, logger) {
  logger.write_string(self.name)
}

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

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

///|
/// Register a type of dependency objects under a name that is unique in the registry.
///
/// `base` is a type of the same registry. The new type finds its properties by name and uses their metadata. `element`
/// says that objects of the type can have a place in the logical tree, which is also so for a type that derives from an
/// element type.
pub fn register_owner_type(
  name : String,
  base? : OwnerType,
  element~ : Bool = false,
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> OwnerType raise DependencyError {
  if name.is_empty() {
    raise InvalidRegistration("an owner type needs a name")
  }
  if base is Some(base) && base.registry_id != registry.id {
    raise RegistryMismatch(
      "`\{name}` cannot derive from `\{base}`, which belongs to another registry",
    )
  }
  if registry.type_names.contains(name) {
    raise InvalidRegistration("`\{name}` is registered already")
  }
  let number = registry.type_names.length()
  registry.type_names.insert(name)
  {
    registry_id: registry.id,
    number,
    name,
    base,
    element: element || (base is Some(base) && base.element),
  }
}

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

///|
pub fn OwnerType::registry_id(self : OwnerType) -> RegistryId {
  self.registry_id
}

///|
pub fn OwnerType::base_type(self : OwnerType) -> OwnerType? {
  self.base
}

///|
/// Whether the type, or a type that it derives from, was registered as an element type.
pub fn OwnerType::is_element(self : OwnerType) -> Bool {
  self.element
}

///|
/// Whether `other` is this type or a type that it derives from.
pub fn OwnerType::derives_from(self : OwnerType, other : OwnerType) -> Bool {
  for next = Some(self); next is Some(owner); next = owner.base {
    if owner == other {
      return true
    }
  }
  false
}

///|
/// What `find` gives for the type itself, or else for the nearest base type for which it gives something.
fn[T] OwnerType::find_base(self : OwnerType, find : (OwnerType) -> T?) -> T? {
  for next = Some(self); next is Some(owner); next = owner.base {
    if find(owner) is Some(found) {
      return Some(found)
    }
  }
  None
}