///|
/// A dependency property without its value type: its identity, and access to its values as `AnyValue`.
///
/// All handles of one property are equal, also one that `lookup_property` gives.
pub struct PropertyInfo {
  priv registry_id : RegistryId
  /// The position in the order of registration, which is also the order of the stored values of an object.
  priv index : Int32
  priv name : String
  priv owner_type : OwnerType
  priv value_key_id : ValueKeyId
  priv attached : Bool
  priv read_only : Bool
  priv equal : (AnyValue, AnyValue) -> Bool
  priv validate : (AnyValue) -> Bool
  priv show : (AnyValue) -> String
  priv default_metadata : Metadata
  /// The metadata for the types that have their own.
  priv overrides : Map[OwnerType, Metadata]
}

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

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

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

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

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

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

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

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

///|
/// The identity of the key that wraps the values of the property.
pub fn PropertyInfo::value_key_id(self : PropertyInfo) -> ValueKeyId {
  self.value_key_id
}

///|
pub fn PropertyInfo::is_attached(self : PropertyInfo) -> Bool {
  self.attached
}

///|
pub fn PropertyInfo::is_read_only(self : PropertyInfo) -> Bool {
  self.read_only
}

///|
/// Whether `a` and `b` are equal values of the property, by the equality that also decides whether a value has changed.
/// A value of another key is equal to nothing.
pub fn PropertyInfo::equal_values(
  self : PropertyInfo,
  a : AnyValue,
  b : AnyValue,
) -> Bool {
  (self.equal)(a, b)
}

///|
/// A dependency property with values of type `T`.
pub struct DependencyProperty[T] {
  priv info : PropertyInfo
  priv key : ValueKey[T]
}

///|
/// The property without its value type.
pub fn[T] DependencyProperty::info(
  self : DependencyProperty[T],
) -> PropertyInfo {
  self.info
}

///|
/// The right to change a read-only property. The code that registers the property gets it, and keeps it private.
pub struct DependencyPropertyKey[T] {
  priv property : DependencyProperty[T]
}

///|
/// The property, which everyone can read.
pub fn[T] DependencyPropertyKey::property(
  self : DependencyPropertyKey[T],
) -> DependencyProperty[T] {
  self.property
}

///|
/// The key without the value type of its property.
pub fn[T] DependencyPropertyKey::info(
  self : DependencyPropertyKey[T],
) -> PropertyKeyInfo {
  { property: self.property.info, }
}

///|
/// The right to change a read-only property, without its value type. Two keys are equal when their properties are.
#derive(Eq, Hash, Debug)
pub struct PropertyKeyInfo {
  priv property : PropertyInfo
}

///|
pub fn PropertyKeyInfo::property(self : PropertyKeyInfo) -> PropertyInfo {
  self.property
}

///|
/// Register a dependency property on `owner`.
///
/// - `key` wraps the values. Its equality decides whether a value has changed, unless `equal` is given.
/// - `default_value` is the value of an object on which nothing is set.
/// - `validate` accepts or rejects a value that is set, and the default value.
/// - `metadata` is for objects of the type `owner` and of the types that derive from it.
///
/// An owner type can have one property with a name. A type that derives from it can use the name for another property.
pub fn[T] register(
  name : String,
  owner : OwnerType,
  key : ValueKey[T],
  default_value~ : T,
  validate? : (T) -> Bool,
  equal? : (T, T) -> Bool,
  metadata? : PropertyMetadata[T],
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> DependencyProperty[T] raise DependencyError {
  registry.register(
    name,
    owner,
    key,
    default_value~,
    validate?,
    equal?,
    metadata?,
    attached=false,
    read_only=false,
  )
}

///|
/// Register a property that its owner type defines for objects of every type, such as `Grid.Row`. The arguments are those
/// of `register`, but `metadata` is for objects of all types.
pub fn[T] register_attached(
  name : String,
  owner : OwnerType,
  key : ValueKey[T],
  default_value~ : T,
  validate? : (T) -> Bool,
  equal? : (T, T) -> Bool,
  metadata? : PropertyMetadata[T],
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> DependencyProperty[T] raise DependencyError {
  registry.register(
    name,
    owner,
    key,
    default_value~,
    validate?,
    equal?,
    metadata?,
    attached=true,
    read_only=false,
  )
}

///|
/// Register a property that only code with the returned key can change. The arguments are those of `register`.
pub fn[T] register_read_only(
  name : String,
  owner : OwnerType,
  key : ValueKey[T],
  default_value~ : T,
  validate? : (T) -> Bool,
  equal? : (T, T) -> Bool,
  metadata? : PropertyMetadata[T],
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> DependencyPropertyKey[T] raise DependencyError {
  let property = registry.register(
    name,
    owner,
    key,
    default_value~,
    validate?,
    equal?,
    metadata?,
    attached=false,
    read_only=true,
  )
  { property, }
}

///|
/// Register an attached property that only code with the returned key can change. The arguments are those of `register`.
pub fn[T] register_attached_read_only(
  name : String,
  owner : OwnerType,
  key : ValueKey[T],
  default_value~ : T,
  validate? : (T) -> Bool,
  equal? : (T, T) -> Bool,
  metadata? : PropertyMetadata[T],
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> DependencyPropertyKey[T] raise DependencyError {
  let property = registry.register(
    name,
    owner,
    key,
    default_value~,
    validate?,
    equal?,
    metadata?,
    attached=true,
    read_only=true,
  )
  { property, }
}

///|
/// The four registrations. A registration that fails registers nothing.
fn[T] PropertyRegistry::register(
  self : PropertyRegistry,
  name : String,
  owner : OwnerType,
  key : ValueKey[T],
  default_value~ : T,
  validate~ : (T) -> Bool = _ => true,
  equal~ : (T, T) -> Bool = key.equal,
  metadata? : PropertyMetadata[T],
  attached~ : Bool,
  read_only~ : Bool,
) -> DependencyProperty[T] raise DependencyError {
  self.check_owner(owner)
  if name.is_empty() {
    raise InvalidRegistration("a property of `\{owner}` needs a name")
  }
  self.check_name(owner, name)
  if metadata is Some({ default_value: Some(_), .. }) {
    raise InvalidRegistration(
      "the metadata of the registration of `\{owner}.\{name}` cannot have a default value, which is the argument `default_value`",
    )
  }
  if !validate(default_value) {
    raise InvalidRegistration(
      "\{key.text(default_value)} is not a valid default value of `\{owner}.\{name}`",
    )
  }
  let plain = Metadata::new(key.wrap(default_value))
  let merged = match metadata {
    Some(metadata) => metadata.merge(plain, key)
    None => plain
  }
  let info = {
    registry_id: self.id,
    index: self.property_count,
    name,
    owner_type: owner,
    value_key_id: key.id,
    attached,
    read_only,
    equal: (a, b) => {
      key.unwrap(a) is Some(a) && key.unwrap(b) is Some(b) && equal(a, b)
    },
    validate: value => validate(key.value_of(value)),
    show: value => key.text(key.value_of(value)),
    default_metadata: if attached {
      merged
    } else {
      plain
    },
    overrides: Map([]),
  }
  // As in WPF, the metadata of an attached property is for all types, and that of another one for its owner type. A
  // read-only property always has metadata for its owner type.
  if !attached && (metadata is Some(_) || read_only) {
    info.overrides[owner] = merged
  }
  self.property_count += 1
  self.properties[(owner, name)] = info
  { info, key, }
}

///|
/// Make the property one of `owner` too, so that `lookup_property` finds it there by its name. Returns the same property.
///
/// `metadata` is for objects of the type `owner`, as with `override_metadata`. A read-only property cannot have it here, but
/// `override_metadata` can give it with the key.
pub fn[T] DependencyProperty::add_owner(
  self : DependencyProperty[T],
  owner : OwnerType,
  metadata? : PropertyMetadata[T],
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> DependencyProperty[T] raise DependencyError {
  let info = self.info
  if owner.registry_id != info.registry_id {
    raise RegistryMismatch(
      "`\{owner}` cannot be an owner of `\{info}`, which belongs to another registry",
    )
  }
  registry.check_owner(owner)
  registry.check_name(owner, info.name)
  if metadata is Some(metadata) {
    self.override_metadata(owner, metadata)
  }
  registry.properties[(owner, info.name)] = info
  self
}

///|
/// The property with the name `name` of `owner`, or else of the nearest type that it derives from.
pub fn lookup_property(
  owner : OwnerType,
  name : String,
  registry~ : PropertyRegistry = PropertyRegistry::default(),
) -> PropertyInfo? raise DependencyError {
  registry.check_owner(owner)
  owner.find_base(owner => registry.properties.get((owner, name)))
}