// The objects that stand for described values while a document is read (design F4 of add-xaml-codecs).

///|
/// An object of the document. It collects the members, because the value is created from all of them together.
priv struct LoadingObject {
  type_name : @nodes.XamlTypeName
  /// The member with the name of the object, if the type has one.
  name_member : String?
  members : Map[String, @nodes.XamlValue]
  create : (Members) -> @nodes.XamlObject raise
  /// The value under the key of its type, from the end of the object.
  mut created : @nodes.XamlObject?
}

///|
/// The key of the loading objects of all types.
let loading_key : @nodes.ObjectKey[LoadingObject] = @nodes.ObjectKey::new()

///|
fn loading_object(value : @nodes.XamlValue) -> LoadingObject? {
  guard value is Object(handle) else { return None }
  loading_key.unwrap(handle)
}

///|
/// The loading object in `target`. Only `root_object` of the settings can be another one.
fn LoadingObject::of(target : @nodes.XamlObject) -> LoadingObject raise {
  guard loading_key.unwrap(target) is Some(object) else {
    raise @schema.ValueError(
      "\{target.type_name} is described by a codec, which cannot fill an object that exists",
    )
  }
  object
}

///|
/// The type and the name of the object, for messages.
fn LoadingObject::describe(self : LoadingObject) -> String {
  match self.name_member.map(name => self.members.get(name)) {
    Some(Some(String(name))) if name != "" => "\{self.type_name} \"\{name}\""
    _ => self.type_name.to_string()
  }
}

///|
/// An object in the members whose value is not created.
fn LoadingObject::unfinished_member(self : LoadingObject) -> LoadingObject? {
  fn find(value) {
    match loading_object(value) {
      Some({ created: None, .. } as object) => Some(object)
      _ => None
    }
  }

  self.members
  .values()
  .filter_map(value => {
    match value {
      Object(handle) if list_key.unwrap(handle) is Some({ items, .. }) =>
        items.iter().filter_map(find).head()
      Object(handle) if map_key.unwrap(handle) is Some({ entries, .. }) =>
        entries.iter().filter_map(entry => find(entry.1)).head()
      _ => find(value)
    }
  })
  .head()
}

///|
/// Create the value when the document has given all members.
///
/// The object writer ends an object after those that it needs. Only in a circle of references it cannot, and begins with one of the
/// objects in the circle.
fn LoadingObject::end(
  self : LoadingObject,
  required : Array[String],
) -> Unit raise {
  for name in required {
    guard self.members.contains(name) else { raise missing_member(name) }
  }
  if self.unfinished_member() is Some(other) {
    let what = if physical_equal(other, self) {
      "itself"
    } else {
      "\{other.describe()}, which needs it too"
    }
    raise @schema.ValueError(
      "\{self.describe()} needs \{what}: a described value cannot be in a circle of references",
    )
  }
  self.created = Some((self.create)({ object: self, }))
}

///|
fn missing_member(name : String) -> @schema.ValueError {
  ValueError("the member \{name} is required")
}