// The default name scope (design D15).

///|
/// `NameScope` in `urn:moonrockz:xaml`, the type of the name scopes that `name_scope_value` wraps.
pub let name_scope_type : @nodes.XamlTypeName = moonrockz_type("NameScope")

///|
/// A name scope that holds its names itself, as System.Xaml `NameScope`: the scope of a document whose root has
/// none of its own.
pub struct NameScope {
  priv names : Map[String, @nodes.XamlValue]
}

///|
/// An empty name scope.
pub fn NameScope::new() -> NameScope {
  { names: Map([]), }
}

///|
/// The object or other value that has the name.
pub fn NameScope::find(self : NameScope, name : String) -> @nodes.XamlValue? {
  self.names.get(name)
}

///|
/// Give `value` the name. The same object can be registered again under its name. Two values are never the
/// same object, also when they are equal, as two boxes are not in .NET.
pub fn NameScope::register(
  self : NameScope,
  name : String,
  value : @nodes.XamlValue,
) -> Unit raise ValueError {
  if !@nodes.is_object_name(name) {
    raise ValueError("\"\{name}\" is not a valid name of an object")
  }
  match (self.names.get(name), value) {
    (None, _) => self.names[name] = value
    (Some(Object(known)), Object(object)) if !object.is_value() &&
      known == object => ()
    (Some(_), _) =>
      raise ValueError("the name \"\{name}\" already belongs to another object")
  }
}

///|
let name_scope_key : @nodes.ObjectKey[NameScope] = @nodes.ObjectKey::new()

///|
/// `scope` as the value of a member, such as a name-scope property.
pub fn name_scope_value(scope : NameScope) -> @nodes.XamlValue {
  Object(name_scope_key.wrap(name_scope_type, scope))
}

///|
/// The scope in a value that `name_scope_value` created.
pub fn as_name_scope(value : @nodes.XamlValue) -> NameScope? {
  match value {
    Object(handle) => name_scope_key.unwrap(handle)
    _ => None
  }
}

///|
fn name_scope_definition() -> XamlTypeDefinition {
  let scope_of = (target : @nodes.XamlObject) => {
    state_of(name_scope_key, target, "NameScope")
  }
  XamlTypeDefinition::new(moonrockz_namespace, "NameScope")
  .object_key(name_scope_key)
  .add_constructor([], (_, _) => name_scope_value(NameScope::new()))
  .name_scope(lookup=(target, name) => scope_of(target).find(name), register=(
    target,
    name,
    value,
  ) => scope_of(target).register(name, value))
}