// The name scopes of the object writer (design D15).

///|
/// A name scope of a loaded object, as .NET `INameScope`. It uses the operations that the type of the scope
/// registers.
pub struct LoadedNameScope {
  /// The object that is the scope: the loaded object itself, the value of its name-scope property, or a
  /// `NameScope` that the writer created.
  object : @nodes.XamlObject
  priv lookup : @schema.NameScopeLookup
  priv record : @schema.NameScopeRegister
}

///|
/// The object or other value that has the name in this scope. Enclosing scopes are not searched.
pub fn LoadedNameScope::find(
  self : LoadedNameScope,
  name : String,
) -> @nodes.XamlValue? raise {
  (self.lookup)(self.object, name)
}

///|
/// Give `value` the name in this scope. It raises when the scope does not accept the name.
pub fn LoadedNameScope::register(
  self : LoadedNameScope,
  name : String,
  value : @nodes.XamlValue,
) -> Unit raise {
  (self.record)(self.object, name, value)
}

///|
/// The scope that `value` of type `type_` is, if it is one.
fn LoadedNameScope::of(
  value : @nodes.XamlValue,
  type_ : @schema.XamlType?,
) -> LoadedNameScope? {
  if value is Object(object) &&
    type_ is Some(type_) &&
    type_.name_scope() is Some(Operations(lookup~, register~)) {
    Some({ object, lookup, record: register, })
  } else {
    None
  }
}

///|
/// The names of an object and its descendants. An object refers to its scope by the index in
/// `NameTable::scopes`, so that a scope and the objects that it names are no cycle of references.
priv struct Scope {
  /// The enclosing scope. The root scope has none.
  parent : Int32?
  /// The type of the object that has the scope.
  type_ : @schema.XamlType
  /// The operations, once there is an object to use them on.
  mut operations : LoadedNameScope?
  /// The objects that this load named in the scope.
  names : Map[String, ObjectFrame]
  /// The references that wait for an object of this scope or, when its names are closed, of an enclosing one.
  waiting : Map[String, Array[Reference]]
  /// Whether the object that has the scope is off the stack.
  mut is_closed : Bool
}

///|
/// The names of a load. The name resolvers keep it, and it is empty when the load is over. So a context that an
/// extension keeps holds nothing of the load but what its fields say, and is in no cycle of references with it.
priv struct NameTable {
  types : TypeLookup
  /// The open objects, the root first.
  objects : Array[ObjectFrame]
  /// The name scopes of the document, the root scope first.
  scopes : Array[Scope]
  mut root : ObjectFrame?
  /// Whether the root has ended, so that no name comes any more.
  mut is_ending : Bool
  /// The objects that name resolvers found since then.
  found : Array[ObjectFrame]
}

///|
/// Remove the elements of `array`, also from its buffer, which `Array::clear` keeps with them on wasm, wasm-gc and
/// native.
fn[T] empty(array : Array[T]) -> Unit {
  array.clear()
  array.shrink_to_fit()
}

///|
fn NameTable::clear(self : NameTable) -> Unit {
  empty(self.objects)
  empty(self.scopes)
  empty(self.found)
  self.root = None
  self.is_ending = true
}

///|
/// The index of the scope of an object of type `type_` inside an object with the scope `parent`.
fn NameTable::scope_index(
  self : NameTable,
  type_ : @schema.XamlType,
  parent : Int32?,
) -> Int32 {
  match parent {
    Some(parent) if !type_.is_name_scope() => parent
    _ => {
      self.scopes.push({
        parent,
        type_,
        operations: None,
        names: Map([]),
        waiting: Map([]),
        is_closed: false,
      })
      self.scopes.length() - 1
    }
  }
}

///|
/// Let the scope that `object` is below the root use its instance, which is new.
fn NameTable::bind_scope(self : NameTable, object : ObjectFrame) -> Unit {
  let scope = self.scopes[object.scope]
  if object.type_.is_name_scope() &&
    scope.parent is Some(_) &&
    object.instance is Some(instance) {
    scope.operations = LoadedNameScope::of(instance, Some(object.runtime))
  }
}

///|
/// The operations of the scope with the index `index`. It raises while there is no object to use them on, as
/// System.Xaml does for names in the `x:Arguments` of a name scope.
fn NameTable::operations(
  self : NameTable,
  index : Int32,
) -> LoadedNameScope raise @schema.ValueError {
  let scope = self.scopes[index]
  if scope.operations is Some(found) {
    return found
  }
  let found = match (scope.parent, self.root) {
    (None, Some(root)) => self.root_scope(root)
    _ => raise no_scope_yet(scope.type_)
  }
  scope.operations = Some(found)
  found
}

///|
fn no_scope_yet(type_ : @schema.XamlType) -> @schema.ValueError {
  ValueError(
    "names cannot be used before the name scope of \{type_.name} is created",
  )
}

///|
/// The scope of the document: the root itself, else the scope in its name-scope property, else a new one
/// (System.Xaml `ObjectWriterContext.HuntAroundForARootNameScope`).
fn NameTable::root_scope(
  self : NameTable,
  root : ObjectFrame,
) -> LoadedNameScope raise @schema.ValueError {
  let property = match root.type_.name_scope() {
    Some(Property(definition)) => Some(definition)
    _ => None
  }
  let instance = match root.instance {
    Some(instance) => instance
    None if property is Some(_) || root.type_.is_name_scope() =>
      raise no_scope_yet(root.type_)
    None => Null
  }
  if LoadedNameScope::of(instance, Some(root.runtime)) is Some(found) {
    return found
  }
  let fresh = @schema.name_scope_value(@schema.NameScope::new())
  let value = match property {
    Some(definition) => root.scope_in(definition, fresh)
    None => fresh
  }
  match LoadedNameScope::of(value, self.type_of(value)) {
    Some(found) => found
    None => {
      let name = property
        .map(definition => member_text(definition.member_name()))
        .unwrap_or("")
      let given = match @schema.value_type_name(value) {
        Some(name) => "a value of \{name}"
        None => value_text(value)
      }
      raise ValueError("\{name} takes a name scope, not \{given}")
    }
  }
}

///|
/// The registered type of `value`.
fn NameTable::type_of(
  self : NameTable,
  value : @nodes.XamlValue,
) -> @schema.XamlType? {
  @schema.value_type_name(value).bind(name => self.types.get_type(name))
}

///|
/// The value of the name-scope property `definition` of the root. An empty property is set to `fresh`.
fn ObjectFrame::scope_in(
  self : ObjectFrame,
  definition : @schema.XamlMember,
  fresh : @nodes.XamlValue,
) -> @nodes.XamlValue raise @schema.ValueError {
  let name = member_text(definition.member_name())
  guard self.instance is Some(Object(instance)) &&
    self.runtime.own_member(definition) is Some(own) &&
    own.getter() is Some(get) else {
    raise ValueError("the name-scope property \{name} has no getter")
  }
  let value = get(instance) catch {
    error =>
      raise ValueError("cannot get \{name}: \{@schema.error_message(error)}")
  }
  if !(value is Null) {
    return value
  }
  guard own.setter() is Some(set) else {
    raise ValueError("the name-scope property \{name} has no setter")
  }
  set(instance, fresh) catch {
    error =>
      raise ValueError("cannot set \{name}: \{@schema.error_message(error)}")
  }
  fresh
}

///|
/// Register `object` under the name `value`, which the node of `site` gives. A scope below the root is named in
/// the enclosing scope, and the root in its own (MAUI and Avalonia, design D15).
fn XamlObjectWriter::register_name(
  self : XamlObjectWriter,
  object : ObjectFrame,
  value : @nodes.XamlValue,
  site : Site,
) -> Unit raise @nodes.XamlWriteError {
  guard value is String(name) else {
    raise site.error("x:Name takes a name, not \{value_text(value)}")
  }
  if !@nodes.is_object_name(name) {
    raise site.error("\{@syntax.quoted(name)} is not a valid x:Name")
  }
  if object.late is Some({ producer, .. }) {
    // An object that a direct reference gives has its own name.
    if producer is Some(_) {
      object.late_name = Some((value, site))
    }
    return
  }
  guard object.instance is Some(instance) else {
    raise site.error("x:Name \{name} has no object")
  }
  let index = if object.type_.is_name_scope() {
    self.table.scopes[object.scope].parent.unwrap_or(object.scope)
  } else {
    object.scope
  }
  let failed = (error : Error) => {
    site.error(
      "cannot register the name \{name}: \{@schema.error_message(error)}",
    )
  }
  let operations = self.table.operations(index) catch {
    error => raise failed(error)
  }
  operations.register(name, instance) catch {
    error => raise failed(error)
  }
  self.table.scopes[index].names[name] = object
  object.name = Some((index, name))
}