// The collections, dictionaries and get objects of the object writer.

///|
/// Start the object that the getter of the open member gives. It is already in its place, so it is not
/// assigned at its end.
fn XamlObjectWriter::start_get_object(
  self : XamlObjectWriter,
  site : Site,
) -> Unit raise @nodes.XamlWriteError {
  // The validator lets a get object start in a member only.
  guard self.objects.last() is Some({ open_member: Some(target), .. } as parent) else {
    return
  }
  if self.skips_object(target, site) {
    return
  }
  guard target.role is Property(definition) else {
    raise site.error("a get object reads a property, and this member is none")
  }
  let name = member_text(definition.member_name())
  let (instance, own) = parent.member_of(definition, target.site)
  guard own.getter() is Some(get) else {
    raise site.error("\{name} of \{parent.type_.name} has no getter")
  }
  let value = get(instance) catch {
    error =>
      raise site.error(
        "cannot get \{name} of \{parent.type_.name}: \{@schema.error_message(error)}",
      )
  }
  if value is Null {
    raise site.error("\{name} of \{parent.type_.name} is null")
  }
  let declared = match definition.value_type {
    Some(value_type) =>
      self.types.resolve_type(value_type) catch {
        error => raise site.error(unknown_type(value_type, error))
      }
    None => self.runtime_type(value, parent.type_)
  }
  let object = self.push_object(declared, site)
  object.instance = Some(value)
  object.runtime = self.runtime_type(value, declared)
  object.retrieved_from = Some(definition)
  self.table.bind_scope(object)
}

///|
/// An add that waits for its item, its key or an earlier add.
priv struct PendingAdd {
  /// The collection that the nodes name, when another one with the same object has the queue.
  container : ObjectFrame?
  mut value : @nodes.XamlValue
  /// The type that says which member is the key of the item. Without one it is the type of the value.
  type_ : @schema.XamlType?
  key : ItemKey
  site : Site
}

///|
/// The type that the nodes give an item. A markup extension is not the item, and its value has its own type, as a value
/// that comes late has.
fn ObjectFrame::item_type(self : ObjectFrame) -> @schema.XamlType? {
  if self.type_.is_markup_extension() || self.late is Some(_) {
    None
  } else {
    Some(self.type_)
  }
}

///|
/// The collections with queued adds. Two members can give one collection, and its adds stay in document order.
priv struct Queues {
  /// Those whose key has a hash.
  hashed : Map[@nodes.XamlObject, ObjectFrame]
  /// The others. The search for one of them takes time for each.
  unhashed : Array[ObjectFrame]
}

///|
/// The collection that is `instance`. Equal values are different collections.
fn Queues::find(self : Queues, instance : @nodes.XamlObject) -> ObjectFrame? {
  if instance.is_value() {
    None
  } else if instance.object_hash() is Some(_) {
    self.hashed.get(instance)
  } else {
    for queue in self.unhashed {
      if queue.instance is Some(Object(other)) && other == instance {
        return Some(queue)
      }
    }
    None
  }
}

///|
fn Queues::clear(self : Queues) -> Unit {
  self.hashed.clear()
  empty(self.unhashed)
}

///|
fn Queues::add(self : Queues, queue : ObjectFrame) -> Unit {
  guard queue.instance is Some(Object(instance)) else { return }
  if instance.object_hash() is Some(_) {
    self.hashed[instance] = queue
  } else {
    queue.queue_index = self.unhashed.length()
    self.unhashed.push(queue)
  }
}

///|
fn Queues::remove(self : Queues, queue : ObjectFrame) -> Unit {
  guard queue.instance is Some(Object(instance)) else { return }
  if instance.object_hash() is Some(_) {
    self.hashed.remove(instance)
  } else if self.unhashed.pop() is Some(last) && !physical_equal(last, queue) {
    last.queue_index = queue.queue_index
    self.unhashed[queue.queue_index] = last
  }
}

///|
/// The object that has the queue of this collection, which is open.
fn ObjectFrame::queue(self : ObjectFrame) -> ObjectFrame {
  match self.open_member {
    Some({ queue: Some(earlier), .. }) if !earlier.is_complete => earlier
    _ => self
  }
}

///|
/// Let an add to the open collection `container` wait.
fn XamlObjectWriter::queue_add(
  self : XamlObjectWriter,
  container : ObjectFrame,
  value : @nodes.XamlValue,
  type_ : @schema.XamlType?,
  key : ItemKey,
  site : Site,
) -> PendingAdd {
  let queue = container.queue()
  if queue.adds.is_empty() {
    self.queues.add(queue)
  }
  let container = if physical_equal(queue, container) {
    None
  } else {
    Some(container)
  }
  let add = { container, value, type_, key, site, }
  queue.adds.push(add)
  add
}

///|
/// Make the adds that wait, in their order. An extension that came as a value is added as it is, as in System.Xaml
/// `XamlObjectWriter.ExecutePendingAdds`.
fn XamlObjectWriter::flush_adds(
  self : XamlObjectWriter,
  object : ObjectFrame,
) -> Unit raise @nodes.XamlWriteError {
  if object.adds.is_empty() {
    return
  }
  self.queues.remove(object)
  for add in object.adds {
    let { container, value, type_, key, site, } = add
    self.add_now(container.unwrap_or(object), value, type_, key, site)
  }
  object.adds.clear()
}

///|
/// Add `value` to the open items of `container`, or queue it behind an earlier add, its key or its own content.
/// `item` is the object that gives it, if one does. A collection evaluates a markup extension unless its item type
/// takes it and is not `x:Object` (System.Xaml `XamlObjectWriter.Logic_DoAssignmentToParentCollection`).
fn XamlObjectWriter::add_item(
  self : XamlObjectWriter,
  container : ObjectFrame,
  item : ObjectFrame?,
  value : @nodes.XamlValue,
  site : Site,
) -> Unit raise @nodes.XamlWriteError {
  let (key, item_type, is_unfinished) = match item {
    Some(item) => (item.key, item.item_type(), item.pending > 0)
    None => ({ value: None, is_pending: false, }, None, false)
  }
  let queue = container.queue()
  let is_queued = !queue.adds.is_empty() || key.is_pending || is_unfinished
  let type_ = container.type_
  let value = match self.extension_of(value) {
    Some((extension, extension_type)) if !is_queued &&
      !type_.is_dictionary() &&
      !(type_.item_type is Some(item_type) &&
      item_type != @schema.object_type &&
      self.types.context.accepts(item_type, value)) => {
      let (scope, services) = match item {
        Some(item) => (item.scope, self.own_services(item))
        None => (container.scope, self.value_services(container))
      }
      produced(scope, () => {
        provide_value(extension, extension_type, services, site)
      })
    }
    _ => value
  }
  if is_queued || fixup_of(value) is Some(_) {
    let add = self.queue_add(container, value, item_type, key, site)
    self.put(queue, Item(add), value, site)
  } else {
    self.add_now(container, value, item_type, key, site)
  }
}

///|
/// Add `value` with the key `key`, or with the key that its member of type `item_type` gives.
fn XamlObjectWriter::add_now(
  self : XamlObjectWriter,
  container : ObjectFrame,
  value : @nodes.XamlValue,
  item_type : @schema.XamlType?,
  key : ItemKey,
  site : Site,
) -> Unit raise @nodes.XamlWriteError {
  let type_ = container.type_
  guard container.instance is Some(Object(instance)) else {
    raise site.error("cannot add an item to a value of \{type_.name}")
  }
  self.check_item(type_, type_.item_type, value, "an item", site)
  let add : () -> Unit raise = if type_.is_dictionary() {
    let key = match key.value {
      Some(key) => key
      None => self.implicit_key(container, item_type, value, site)
    }
    self.check_item(type_, type_.key_type, key, "an x:Key", site)
    guard container.runtime.entry_adder() is Some(add) else {
      raise site.error("\{container.runtime.name} takes no keys")
    }
    () => add(instance, key, value)
  } else {
    guard container.runtime.item_adder() is Some(add) else {
      raise site.error("\{container.runtime.name} takes no items without keys")
    }
    () => add(instance, value)
  }
  add() catch {
    error =>
      raise site.error(
        "cannot add \{value_text(value)} to \{type_.name}: \{@schema.error_message(error)}",
      )
  }
}

///|
/// Check that `value`, the item or key `what`, is a value of `expected`, which the container `type_`
/// declares.
fn XamlObjectWriter::check_item(
  self : XamlObjectWriter,
  type_ : @schema.XamlType,
  expected : @nodes.XamlTypeName?,
  value : @nodes.XamlValue,
  what : String,
  site : Site,
) -> Unit raise @nodes.XamlWriteError {
  if expected is Some(expected) && !self.types.context.accepts(expected, value) {
    raise site.error(
      "\{type_.name} takes \{what} of \{expected}, not \{value_text(value)}",
    )
  }
}

///|
/// The key of a dictionary item without `x:Key`: the value of the member that is the `x:Key` alias of its
/// type (System.Xaml `XamlObjectWriter.GetKeyFromInstance`).
fn XamlObjectWriter::implicit_key(
  self : XamlObjectWriter,
  container : ObjectFrame,
  item_type : @schema.XamlType?,
  value : @nodes.XamlValue,
  site : Site,
) -> @nodes.XamlValue raise @nodes.XamlWriteError {
  let type_ = if item_type is Some(_) {
    item_type
  } else {
    self.table.type_of(value)
  }
  guard type_ is Some(type_) &&
    type_.aliased_member(Key) is Some(definition) &&
    value is Object(instance) else {
    let place = match container.retrieved_from {
      Some(member_) => member_text(member_.member_name())
      None => container.type_.name.to_string()
    }
    raise site.error("\{value_text(value)} has no x:Key in \{place}")
  }
  let name = member_text(definition.member_name())
  guard self.runtime_type(value, type_).own_member(definition) is Some(own) &&
    own.getter() is Some(get) else {
    raise site.error("\{name}, the x:Key of \{type_.name}, has no getter")
  }
  get(instance) catch {
    error =>
      raise site.error(
        "cannot get \{name}, the x:Key of \{type_.name}: \{@schema.error_message(error)}",
      )
  }
}

///|
/// The text `value` of `x:Key` as a key of the dictionary that holds `object`.
fn XamlObjectWriter::convert_key(
  self : XamlObjectWriter,
  object : ObjectFrame,
  value : @nodes.XamlValue,
  site : Site,
) -> @nodes.XamlValue raise @nodes.XamlWriteError {
  guard self.is_dictionary_entry(self.objects.length() - 1) &&
    self.objects.get(self.objects.length() - 2) is Some({ type_, .. }) &&
    type_.key_type is Some(key_type) &&
    self.types.get_type(key_type) is Some(key_type) else {
    return value
  }
  convert_to(
    object.scope,
    key_type,
    value,
    self.value_services(object),
    site,
    "x:Key",
  )
}

///|
/// Give the innermost object `object` the key `key`. One that waits delays the dictionary and not the item, whose add
/// waits for it, and outside a collection or member no one uses it (System.Xaml `Logic_PendKeyFixupToken`).
fn XamlObjectWriter::set_key(
  self : XamlObjectWriter,
  object : ObjectFrame,
  key : @nodes.XamlValue,
  site : Site,
) -> Unit raise @nodes.XamlWriteError {
  let holder = if fixup_of(key) is Some(_) {
    guard self.objects.get(self.objects.length() - 2)
      is Some({ instance: Some(_), .. } as container) else {
      return
    }
    object.key.is_pending = true
    container.queue()
  } else {
    object
  }
  self.put(holder, Key(object.key), key, site)
}