// How the mode `SystemXaml` chooses forms: as the states of System.Xaml `XamlXmlWriter` do (design D26), but
// with all nodes of the document at hand.

///|
/// The forms of the members of `object`. They are attributes up to the first member that cannot be one
/// (`InRecordTryAttributes`, `XamlXmlWriter.cs:1112-1211`). A get object has no attributes.
fn Writing::system_xaml_layout(
  self : Writing,
  object : ObjectNode,
  outer_space : Bool,
) -> Layout raise Unwritable {
  let attributes = []
  let body : Array[BodyMember] = []
  for index, m in object.members {
    let is_content = is_content_member(object.type_, m)
    let is_content_text = is_content &&
      m.target.definition is Some(definition) &&
      self.takes_text(definition)
    let text = if body.is_empty() &&
      object.kind != Got &&
      self.tries_attribute(object, m, is_content, is_content_text) &&
      m.values is [first, ..] {
      // `InMemberTryAttributes` and `TryCurlyForm`.
      Some(self.system_xaml_text(first)) catch {
        _ => None
      }
    } else {
      None
    }
    if text is Some(_) && m.values.length() == 1 {
      attributes.push(index)
      continue
    }
    let label = m.target.label()
    if m.values.is_empty() {
      // No state with an open member and no value has `WriteEndMember`.
      raise Unwritable(m.end, "\{label} has no value")
    }
    for place in 1.. Some(text)
        _ => text
      },
    })
  }
  {
    attributes,
    body,
    adds_space: false,
    preserves_space: own_space(object).unwrap_or(outer_space),
    keeps_end_tag: false,
  }
}

///|
/// Whether `XamlXmlWriter` looks for an attribute form of `m`, when the members before it are attributes.
fn Writing::tries_attribute(
  self : Writing,
  object : ObjectNode,
  m : MemberNode,
  is_content : Bool,
  is_content_text : Bool,
) -> Bool {
  if is_implicit(m.target) {
    return false
  }
  // A member with a namespace needs a prefix in scope (`XamlXmlWriter.cs:1140-1153`).
  if !(m.target.name is Member(..)) &&
    !(self.member_spelling(object.type_, object, m, Attribute) is Some(spelling) &&
    self.lookup(spelling) is Some((_, false))) {
    return false
  }
  if is_content {
    // `TryContentPropertyInTryAttributesState`.
    return m.values is [Text(text, _), ..] && (text == "" || !is_content_text)
  }
  !(m.target.definition is Some(definition) &&
  definition.is_collection_directive())
}

///|
/// The attribute value for `item`. An object is written in braces with the names in scope, as
/// `XamlMarkupExtensionWriter` does. An error means that it needs an element.
fn Writing::system_xaml_text(
  self : Writing,
  item : Item,
) -> String raise Unwritable {
  if item is Object(id) {
    let object = self.document.objects[id]
    // `InMemberTryAttributes.WriteObject` does not try it for a generic type.
    if self.braces[id] == NoBraces || object.type_.name.arity() > 0 {
      raise Unwritable(object.start, "the object needs an element")
    }
  }
  self.attribute_text(item, (spelling, index, label) => {
    match self.lookup(spelling) {
      Some((name, _)) => name
      None => raise Unwritable(index, "\{label} has no prefix in scope")
    }
  })
}

///|
/// Whether `XamlMarkupExtensionWriter` can write `object`, apart from missing prefixes.
fn Writing::system_xaml_braces(
  self : Writing,
  object : ObjectNode,
) -> BracesForm {
  let is_extension = object.type_.definition is Some(definition) &&
    definition.is_markup_extension()
  if object.kind is Got || !is_extension || !object.declarations.is_empty() {
    return NoBraces
  }
  for index, m in object.members {
    let is_allowed = if is_positional(m) {
      // The type arguments of a generic type come first, and then no state takes positional parameters.
      index == 0 && !m.values.is_empty() && object.type_.name.arity() == 0
    } else {
      m.values.length() == 1 &&
      !is_implicit(m.target) &&
      !(m.target.definition is Some(definition) &&
      definition.is_collection_directive())
    }
    if !is_allowed ||
      m.values
      .iter()
      .any(item => item is Object(child) && self.braces[child] is NoBraces) {
      return NoBraces
    }
  }
  Usual
}

///|
/// Add `xml:space="preserve"` where `XamlXmlWriter` does before it writes `text`, the last value of the member
/// at the place of `open`, or report that it cannot (`InMember.WriteValue`, `XamlXmlWriter.cs:1246-1323`, and
/// `InMemberAfterValueWithSignificantWhitespace`, `:1460-1502`).
fn Writing::add_system_xaml_space(
  self : Writing,
  open : OpenObject,
  text : String,
  index : Int32,
) -> Unit raise Unwritable {
  let has_inner_space = text.contains("\t") ||
    text.contains("\n") ||
    text.contains("\r") ||
    // `ContainsConsecutiveInnerSpaces` starts at the second character.
    (text.length() > 1 && text[1:].contains("  "))
  let starts_with_space = text.has_prefix(" ")
  let ends_with_space = text.has_suffix(" ")
  if !has_inner_space && !starts_with_space && !ends_with_space {
    return
  }
  let m = open.object.members[open.layout.body[open.place].index]
  // `isFirstElementOfWhitespaceSignificantCollection`.
  let is_first = open.value_index == 1 &&
    (
      m.target.name == @syntax.unknown_content_directive ||
      (
        m.target.name == @syntax.items_directive &&
        is_significant(open.object.type_.definition)
      )
    )
  let is_last = open.value_index == m.values.length()
  if self.is_in_significant_collection(open.object, m) {
    // A space at the start or the end is kept without the attribute when another item is there.
    let is_kept = !has_inner_space &&
      !(is_first && starts_with_space) &&
      !(is_last && ends_with_space)
    if is_kept {
      return
    }
    if !is_first {
      raise Unwritable(
        index, "the white space of this text in a collection can only be kept in its first item",
      )
    }
    if !has_inner_space && !starts_with_space {
      // The state after trailing white space does not look for a property element.
      self.add_space_attribute(index)
      return
    }
  }
  if self.element_member() is Some(label) {
    raise Unwritable(
      index,
      "xml:space=\"preserve\" cannot be written on a member, but the white space of this text in \{label} needs it",
    )
  }
  self.add_space_attribute(index)
}

///|
/// The member of which the innermost open element is, or `None` when it is an object
/// (`FindFrameWithXmlSpacePreserve`).
fn Writing::element_member(self : Writing) -> String? {
  for open in self.open.rev_iter() {
    let part = open.layout.body[open.place]
    if part.has_tag {
      return Some(open.object.members[part.index].target.label())
    }
    if open.object.kind != Got {
      return None
    }
  }
  None
}

///|
/// Whether `XamlXmlWriter.GetContainingXamlType` finds a white-space significant collection, or nothing that
/// it knows, for a value of `m`.
fn Writing::is_in_significant_collection(
  self : Writing,
  object : ObjectNode,
  m : MemberNode,
) -> Bool {
  if m.target.name == @syntax.items_directive {
    return is_significant(object.type_.definition)
  }
  guard m.target.definition is Some(definition) &&
    m.target.name != @syntax.unknown_content_directive else {
    return true
  }
  guard definition.value_type is Some(value_type) else { return false }
  is_significant(self.document.types.get_type(value_type))
}

///|
/// Unknown types count as white-space significant collections (`TypeReflector.UnknownReflector`).
fn is_significant(definition : @schema.XamlType?) -> Bool {
  match definition {
    Some(definition) => definition.is_whitespace_significant_collection()
    None => true
  }
}

///|
/// Add `xml:space="preserve"` to the open start tag for the node `index`. Like an `XmlWriter`, it fails when
/// the tag has ended or already has the attribute.
fn Writing::add_space_attribute(
  self : Writing,
  index : Int32,
) -> Unit raise Unwritable {
  guard self.output.tag is Some(tag) else {
    raise Unwritable(
      index, "the white space of this text needs xml:space=\"preserve\", but its element already has content",
    )
  }
  if tag.attributes.iter().any(attribute => attribute.0 == "xml:space") {
    raise Unwritable(
      index, "the white space of this text needs xml:space=\"preserve\", but its element already has the attribute xml:space",
    )
  }
  tag.attributes.push(("xml:space", "preserve"))
}