// The XML text with the namespace scopes of its open elements. The last start tag stays open until its
// content comes, so it can get declarations and attributes after its name.

///|
priv struct XmlOutput {
  text : StringBuilder
  /// The start tag that has no end yet.
  mut tag : StartTag?
  /// The names of the open elements, the innermost last.
  open : Array[String]
  /// The declarations in scope, the innermost last.
  declared : Array[Declaration]
  /// The places in `declared` of each prefix.
  places : Map[String, Array[Int32]]
  /// The places in `declared` of each namespace.
  namespaces : Map[String, Array[Int32]]
  /// The length of `declared` before each open element.
  scopes : Array[Int32]
  /// The namespace of each prefix in the document. `None` for a prefix with more than one.
  history : Map[String, String?]
  /// The prefixes that the document had for each namespace before any other one.
  first_prefixes : Map[String, Array[String]]
  /// For each base, a number below which the document has all numbered prefixes.
  numbers : Map[String, Int32]
}

///|
priv struct Declaration {
  prefix : String
  namespace_uri : String
  /// The number of open elements around the content of the element that has the declaration.
  depth : Int32
}

///|
priv struct StartTag {
  mut name : String
  declarations : Array[(String, String)]
  attributes : Array[(String, String)]
  /// Whether a name in it is in the default namespace of an outer element or of the tag.
  mut uses_default : Bool
}

///|
fn XmlOutput::new() -> XmlOutput {
  let output = {
    text: StringBuilder(),
    tag: None,
    open: [],
    declared: [],
    places: Map([]),
    namespaces: Map([]),
    scopes: [],
    history: Map([]),
    first_prefixes: Map([]),
    numbers: Map([]),
  }
  output.bring_into_scope("xml", @schema.xml_namespace)
  // An unprefixed element without a default namespace has no namespace.
  output.bring_into_scope("", "")
  output
}

///|
/// Start an element, on a line of its own when `on_new_line`. Its name comes later, because it can need a
/// declaration on the element.
fn XmlOutput::start_element(self : XmlOutput, on_new_line~ : Bool) -> StartTag {
  self.end_tag(">")
  if on_new_line {
    self.start_line()
  }
  let tag = { name: "", declarations: [], attributes: [], uses_default: false, }
  self.tag = Some(tag)
  self.scopes.push(self.declared.length())
  tag
}

///|
/// End the innermost element. `keeps_end_tag` writes `` and not `` for an empty element, and
/// `on_new_line` puts the end tag of another one on a line of its own.
fn XmlOutput::end_element(
  self : XmlOutput,
  keeps_end_tag~ : Bool,
  on_new_line~ : Bool,
) -> Unit {
  if self.tag is Some(_) && !keeps_end_tag {
    self.end_tag("/>")
    ignore(self.open.pop())
  } else {
    let is_empty = self.tag is Some(_)
    self.end_tag(">")
    if self.open.pop() is Some(name) {
      if on_new_line && !is_empty {
        self.start_line()
      }
      self.text.write_string("")
    }
  }
  let scope = self.scopes.pop().unwrap_or(0)
  while self.declared.length() > scope && self.declared.pop() is Some(entry) {
    if self.places.get(entry.prefix) is Some(places) {
      ignore(places.pop())
    }
    if self.namespaces.get(entry.namespace_uri) is Some(places) {
      ignore(places.pop())
    }
  }
}

///|
/// Write the open start tag and `end`.
fn XmlOutput::end_tag(self : XmlOutput, end : String) -> Unit {
  guard self.tag is Some(tag) else { return }
  self.tag = None
  self.open.push(tag.name)
  self.text.write_string("<\{tag.name}")
  tag.declarations.sort_by((left, right) => left.0.lexical_compare(right.0))
  for declaration in tag.declarations {
    let (prefix, namespace_uri) = declaration
    let name = if prefix == "" { "xmlns" } else { "xmlns:\{prefix}" }
    self.write_attribute(name, namespace_uri)
  }
  for attribute in tag.attributes {
    self.write_attribute(attribute.0, attribute.1)
  }
  self.text.write_string(end)
}

///|
fn XmlOutput::write_attribute(
  self : XmlOutput,
  name : String,
  value : String,
) -> Unit {
  self.text.write_string(" \{name}=\"")
  self.write_escaped(value, in_attribute=true)
  self.text.write_char('"')
}

///|
fn XmlOutput::write_text(self : XmlOutput, text : String) -> Unit {
  self.end_tag(">")
  self.write_escaped(text, in_attribute=false)
}

///|
/// Start a line with two spaces for each open element.
fn XmlOutput::start_line(self : XmlOutput) -> Unit {
  if self.text.is_empty() {
    return
  }
  self.text.write_char('\n')
  for _ in 0.. Unit {
  let mut start = 0
  for offset in 0.. "&"
      '<' => "<"
      '>' => ">"
      '\r' => "
"
      '"' if in_attribute => """
      '\t' if in_attribute => "	"
      '\n' if in_attribute => "
"
      _ => continue
    }
    self.text.write_substring(text, start, offset - start)
    self.text.write_string(escaped)
    start = offset + 1
  }
  self.text.write_substring(text, start, text.length() - start)
}

///|
/// Declare `prefix` on the open start tag.
fn XmlOutput::declare_prefix(
  self : XmlOutput,
  prefix : String,
  namespace_uri : String,
) -> Unit {
  if self.tag is Some(tag) {
    tag.declarations.push((prefix, namespace_uri))
  }
  self.use_prefix(prefix, namespace_uri)
  self.bring_into_scope(prefix, namespace_uri)
}

///|
fn XmlOutput::bring_into_scope(
  self : XmlOutput,
  prefix : String,
  namespace_uri : String,
) -> Unit {
  let place = self.declared.length()
  self.places.get_or_init(prefix, () => []).push(place)
  self.namespaces.get_or_init(namespace_uri, () => []).push(place)
  self.declared.push({ prefix, namespace_uri, depth: self.scopes.length(), })
}

///|
/// Remember that the document has `prefix` for `namespace_uri`.
fn XmlOutput::use_prefix(
  self : XmlOutput,
  prefix : String,
  namespace_uri : String,
) -> Unit {
  match self.history.get(prefix) {
    None => {
      self.history.set(prefix, Some(namespace_uri))
      self.first_prefixes.get_or_init(namespace_uri, () => []).push(prefix)
    }
    Some(earlier) if earlier != Some(namespace_uri) =>
      self.history.set(prefix, None)
    Some(_) => ()
  }
}

///|
fn XmlOutput::is_free(
  self : XmlOutput,
  prefix : String,
  namespace_uri : String,
) -> Bool {
  match self.history.get(prefix) {
    Some(earlier) => earlier == Some(namespace_uri)
    None => true
  }
}

///|
/// `base`, or `base1`, `base2` and so on, the first that the document has for no other namespace.
fn XmlOutput::free_prefix(
  self : XmlOutput,
  base : String,
  namespace_uri : String,
) -> String {
  let mut number = self.numbers.get(base).unwrap_or(0)
  while self.history.contains(numbered(base, number)) {
    number += 1
  }
  self.numbers.set(base, number)
  for prefix in self.first_prefixes.get(namespace_uri).unwrap_or([]) {
    if self.is_free(prefix, namespace_uri) &&
      number_after(prefix, base) is Some(earlier) &&
      earlier < number {
      number = earlier
    }
  }
  numbered(base, number)
}

///|
fn numbered(base : String, number : Int32) -> String {
  if number == 0 {
    base
  } else {
    "\{base}\{number}"
  }
}

///|
/// The number for which `numbered` gives `prefix`.
fn number_after(prefix : String, base : String) -> Int32? {
  guard prefix.strip_prefix(base) is Some(digits) else { return None }
  if digits.has_prefix("0") || digits.length() > 9 {
    return None
  }
  let mut number = 0
  for digit in digits {
    guard digit is ('0'..<='9') else { return None }
    number = number * 10 + (digit.to_int() - '0'.to_int())
  }
  Some(number)
}

///|
/// Whether an inner declaration of its prefix hides the declaration at `place`.
fn XmlOutput::is_shadowed(self : XmlOutput, place : Int32) -> Bool {
  self.places.get(self.declared[place].prefix).bind(places => places.last()) !=
  Some(place)
}

///|
/// Whether one of `places` is a declaration on the innermost element.
fn XmlOutput::is_innermost(self : XmlOutput, places : Array[Int32]?) -> Bool {
  places is Some([.., last]) &&
  self.scopes.last() is Some(scope) &&
  last >= scope
}

///|
/// The namespace of `prefix` in the scope of the open elements.
fn XmlOutput::namespace_of(self : XmlOutput, prefix : String) -> String {
  match self.places.get(prefix).bind(places => places.last()) {
    Some(place) => self.declared[place].namespace_uri
    None => ""
  }
}