// The traversal that writes a document. A mode only chooses the forms of the members of each object.

///|
/// A document while it is written.
priv struct Writing {
  mode : WriterMode
  document : Document
  /// The lookups of the reader.
  names : @syntax.Names
  output : XmlOutput
  /// The names of types in namespaces.
  type_names : Map[(@nodes.XamlTypeName, String, TypePlace), String?]
  /// How each object can be written in braces.
  braces : Array[BracesForm]
  /// For each object with braces, whether an element can be read as the same nodes.
  keeps_nodes : Array[Bool]
  demands : Array[Demand]
  /// The namespaces of the directives in the document.
  directive_namespaces : Map[String, Unit]
  open : Array[OpenObject]
}

///|
/// An object that is written up to some member and value.
priv struct OpenObject {
  object : ObjectNode
  /// The type in the namespace of the element.
  element : @syntax.NamedType
  layout : Layout
  /// The place in the body.
  mut place : Int32
  /// The index of the next value of the member at `place`. -1 before its start tag.
  mut value_index : Int32
  /// Whether the elements in the element are on lines of their own.
  is_indented : Bool
  /// Whether those of the member at `place` are, when it has an element of its own.
  mut is_member_indented : Bool
}

///|
/// Whether a type that the nodes of `object` name, or one of its type arguments, has no namespace.
fn has_name_without_namespace(object : ObjectNode) -> Bool {
  let names = [object.type_.name]
  for m in object.members {
    if m.target.name is (Member(owner~, ..) | Attached(owner~, ..)) {
      names.push(owner)
    }
  }
  while names.pop() is Some(name) {
    if name.namespace_uri == "" {
      return true
    }
    names.append(name.type_arguments.iter().collect())
  }
  false
}

///|
/// The text of `document`, of which the root object has ended.
fn write_document(
  document : Document,
  mode : WriterMode,
  indent~ : Bool,
) -> String raise Unwritable {
  let count = document.objects.length()
  let output = XmlOutput::new()
  let writing = {
    mode,
    document,
    names: {
      types: document.types,
      local_scope: None,
      // Names are looked up by their namespaces, never by prefixes.
      namespace_of: _ => None,
    },
    output,
    type_names: Map([]),
    braces: Array::make(count, NoBraces),
    keeps_nodes: Array::make(count, true),
    demands: Array::makei(count, _ => Demand::new()),
    directive_namespaces: Map([]),
    open: [],
  }
  if mode is RoundTrip {
    // A generated prefix cannot be one that the stream uses for another namespace, also further on.
    for object in document.objects {
      for declaration in object.declarations {
        output.use_prefix(declaration.0, declaration.1)
      }
      for m in object.members {
        if m.target.name
          is (Directive(namespace_uri~, ..)
          | UnknownDirective(namespace_uri~, ..)) &&
          !is_implicit(m.target) {
          writing.directive_namespaces.set(namespace_uri, ())
        }
      }
    }
    if document.objects.iter().any(has_name_without_namespace) {
      output.use_prefix("", "")
    }
  }
  writing.check_braces()
  writing.start_object(0, false, indent)
  while writing.open.last() is Some(open) {
    writing.advance(open)
  }
  output.text.to_string()
}

///|
/// Write the next tag or value in `open`, the innermost object.
fn Writing::advance(self : Writing, open : OpenObject) -> Unit raise Unwritable {
  let object = open.object
  guard open.layout.body.get(open.place) is Some(part) else {
    ignore(self.open.pop())
    if object.kind != Got {
      self.output.end_element(
        keeps_end_tag=open.layout.keeps_end_tag,
        on_new_line=open.is_indented,
      )
    }
    return
  }
  let m = object.members[part.index]
  if open.value_index < 0 {
    open.value_index = 0
    open.is_member_indented = open.is_indented
    if part.has_tag {
      let tag = self.output.start_element(on_new_line=open.is_indented)
      tag.name = self.tag_name(open.element, object, m)
      open.is_member_indented = open.is_indented &&
        part.first_text is None &&
        !m.target.holds_space(self.document.types) &&
        !self.has_text(m)
    }
  }
  match m.values.get(open.value_index) {
    Some(item) => {
      open.value_index += 1
      match item {
        _ if open.value_index == 1 && part.first_text is Some(text) =>
          self.output.write_text(text)
        Text(text, index) => {
          if self.mode is SystemXaml {
            self.add_system_xaml_space(open, text, index)
          }
          self.output.write_text(text)
        }
        Object(child) =>
          self.start_object(
            child,
            open.layout.preserves_space,
            open.is_member_indented,
          )
      }
    }
    None => {
      if part.has_tag {
        self.output.end_element(
          keeps_end_tag=false,
          on_new_line=open.is_member_indented,
        )
      }
      open.place += 1
      open.value_index = -1
    }
  }
}

///|
/// Whether the element around the values of `m` has text.
fn Writing::has_text(self : Writing, m : MemberNode) -> Bool {
  self.document.items(m).0.iter().any(item => item is Text(_, _))
}

///|
/// Whether the elements in the element of `object` can be on lines of their own, so that the reader ignores
/// the white space between them.
fn Writing::can_indent(
  self : Writing,
  object : ObjectNode,
  element : @syntax.NamedType,
  layout : Layout,
) -> Bool {
  !layout.preserves_space &&
  layout.body
  .iter()
  .all(part => {
    let m = object.members[part.index]
    part.has_tag ||
    (
      !element.holds_space(self.document.types) &&
      m.target.name != @syntax.unknown_content_directive &&
      !self.has_text(m)
    )
  })
}

///|
fn Writing::tag_name(
  self : Writing,
  element : @syntax.NamedType,
  object : ObjectNode,
  m : MemberNode,
) -> String raise Unwritable {
  let label = m.target.label()
  guard self.tag_spelling(element, object, m) is Some(spelling) else {
    raise Unwritable(m.start, "\{label} cannot be written as an element")
  }
  self.spell(spelling, m.start, label)
}

///|
/// Start the object `id`, on a line of its own when `is_indented`, in an element where white space is
/// preserved when `outer_space`.
fn Writing::start_object(
  self : Writing,
  id : Int32,
  outer_space : Bool,
  is_indented : Bool,
) -> Unit raise Unwritable {
  let object = self.document.objects[id]
  if object.kind is Got {
    let element = object.type_
    self.open.push({
      object,
      element,
      layout: if self.mode is SystemXaml {
        self.system_xaml_layout(object, outer_space)
      } else {
        {
          attributes: [],
          body: object.members.mapi((index, m) => {
            index,
            has_tag: !is_implicit(m.target),
            first_text: None,
          }),
          adds_space: false,
          preserves_space: outer_space,
          keeps_end_tag: false,
        }
      },
      place: 0,
      value_index: -1,
      is_indented,
      is_member_indented: is_indented,
    })
    return
  }
  expand_positional(object)
  let tag = self.output.start_element(on_new_line=is_indented)
  let declarations = object.declarations.copy()
  // The declaration with the least prefix is found first.
  declarations.sort_by((left, right) => right.0.lexical_compare(left.0))
  for declaration in declarations {
    self.output.declare_prefix(declaration.0, declaration.1)
  }
  let label = object.type_.name.name
  tag.name = self.spell(self.element_spelling(object), object.start, label)
  let (prefix, local_name) = match tag.name.find(":") {
    Some(colon) =>
      (tag.name[:colon].to_owned(), tag.name[colon + 1:].to_owned())
    None => ("", tag.name)
  }
  let namespace_uri = self.output.namespace_of(prefix)
  let element = self
    .type_back(object.type_, namespace_uri, local_name, Element)
    .unwrap_or(object.type_)
  let layout = if self.mode is SystemXaml {
    if element.name.arity() > 0 {
      ignore(
        self.type_arguments_text(element, object.start, (spelling, index, label) => {
          self.spell(spelling, index, label)
        }),
      )
      ignore(
        self.spell(
          self.type_arguments_spelling(),
          object.start,
          "TypeArguments",
        ),
      )
    }
    self.system_xaml_layout(object, outer_space)
  } else {
    self.round_trip_form(id, element, outer_space, tag)
  }
  for
    attribute in self.attributes(object, element, layout, (
      spelling,
      index,
      label,
    ) => self.spell(spelling, index, label)) {
    tag.attributes.push(attribute)
  }
  let is_indented = is_indented && self.can_indent(object, element, layout)
  self.open.push({
    object,
    element,
    layout,
    place: 0,
    value_index: -1,
    is_indented,
    is_member_indented: is_indented,
  })
}

///|
/// The layout of the object `id`, of which the element `element` has the start tag `tag`. All its names have
/// their declarations.
fn Writing::round_trip_form(
  self : Writing,
  id : Int32,
  element : @syntax.NamedType,
  outer_space : Bool,
  tag : StartTag,
) -> Layout raise Unwritable {
  let object = self.document.objects[id]
  let layout = self.round_trip_layout(id, element, outer_space)
  let demand = self.demands[id]
  let keeps_end_tag = layout.keeps_end_tag ||
    (demand.end_tag && layout.body.is_empty())
  if keeps_end_tag && !layout.keeps_end_tag && element.needs_initialization() {
    raise Unwritable(
      object.start,
      "the reader would give the object an empty initialization text",
    )
  }
  self.declare_names(object, element, layout)
  if demand.no_declarations &&
    tag.declarations.length() > object.declarations.length() {
    raise Unwritable(
      object.start,
      "the element needs a namespace declaration, and the reader would change the white space before it",
    )
  }
  { ..layout, keeps_end_tag, }
}

///|
/// The attributes of the element of `object` that are not declarations.
fn Writing::attributes(
  self : Writing,
  object : ObjectNode,
  element : @syntax.NamedType,
  layout : Layout,
  name_of : (Spelling, Int32, String) -> String raise Unwritable,
) -> Array[(String, String)] raise Unwritable {
  let attributes = []
  if element.name.arity() > 0 {
    let name = name_of(
      self.type_arguments_spelling(),
      object.start,
      "TypeArguments",
    )
    attributes.push(
      (name, self.type_arguments_text(element, object.start, name_of)),
    )
  }
  for index in layout.attributes {
    let m = object.members[index]
    let label = m.target.label()
    guard self.member_spelling(element, object, m, Attribute) is Some(spelling) &&
      m.values is [item] else {
      raise Unwritable(m.start, "\{label} cannot be written as an attribute")
    }
    let name = name_of(spelling, m.start, label)
    let text = if self.mode is SystemXaml {
      self.system_xaml_text(item)
    } else {
      self.attribute_text(item, name_of)
    }
    attributes.push((name, text))
  }
  if layout.adds_space {
    attributes.push(("xml:space", "preserve"))
  }
  attributes
}

///|
/// Declare the namespaces of all names in the start tag and in the tags of the members on the element of
/// the object. Those that need a prefix come first, so that the others can use it.
fn Writing::declare_names(
  self : Writing,
  object : ObjectNode,
  element : @syntax.NamedType,
  layout : Layout,
) -> Unit raise Unwritable {
  let names = []
  ignore(
    self.attributes(object, element, layout, (spelling, index, label) => {
      names.push((spelling, index, label))
      ""
    }),
  )
  for part in layout.body {
    let m = object.members[part.index]
    if part.has_tag && self.tag_spelling(element, object, m) is Some(spelling) {
      names.push((spelling, m.start, m.target.label()))
    }
  }
  for needs_prefix in [true, false] {
    for name in names {
      if (name.0 is Qualified(needs_prefix=true, ..)) == needs_prefix {
        ignore(self.spell(name.0, name.1, name.2))
      }
    }
  }
}

///|
fn Writing::type_arguments_spelling(self : Writing) -> Spelling {
  Qualified(
    local_name=uri => {
      if @syntax.is_language_namespace(uri) {
        Some("TypeArguments")
      } else {
        None
      }
    },
    namespaces=UriChoices::new([@nodes.xaml_language_namespace]),
    needs_prefix=self.mode is RoundTrip,
  )
}