// The nodes of a document as a tree. Objects are numbered in the order of their start nodes, so each
// comes before the objects in it. No object holds another one, so dropping a deep tree does not recurse.

///|
/// The node with this index cannot be written, for this reason.
priv suberror Unwritable {
  Unwritable(Int32, String)
}

///|
priv struct Document {
  types : @syntax.TypeLookup
  nodes : Array[(@nodes.XamlNode, @nodes.SourceSpan?)]
  objects : Array[ObjectNode]
  /// The objects that are open, the innermost last.
  open : Array[Int32]
  /// The prefixes and URIs that are declared before the next start object.
  declarations : Array[(String, String)]
  /// The prefixes in `declarations`.
  mut prefixes : Map[String, Unit]
  /// The prefix of each namespace in `declarations`.
  mut prefix_of : Map[String, String]
}

///|
priv struct ObjectNode {
  /// The index of the start node.
  start : Int32
  kind : ObjectKind
  /// The type. For a get object it is the type of the member that holds the object.
  type_ : @syntax.NamedType
  /// The prefixes and URIs that the stream declares on the object.
  declarations : Array[(String, String)]
  members : Array[MemberNode]
}

///|
#derive(Eq)
priv enum ObjectKind {
  Started
  Got
  /// A null value, written as `x:Null`.
  Null
}

///|
priv struct MemberNode {
  /// The index of the start member.
  start : Int32
  /// The index of the end member.
  mut end : Int32
  target : @syntax.NamedMember
  values : Array[Item]
}

///|
priv enum Item {
  /// Text, and the index of its node.
  Text(String, Int32)
  /// An index in `Document.objects`.
  Object(Int32)
}

///|
fn Document::new(types : @syntax.TypeLookup) -> Document {
  {
    types,
    nodes: [],
    objects: [],
    open: [],
    declarations: [],
    prefixes: Map([]),
    prefix_of: Map([]),
  }
}

///|
/// The index of the node that `item` starts with.
fn Document::index_of(self : Document, item : Item) -> Int32 {
  match item {
    Text(_, index) => index
    Object(id) => self.objects[id].start
  }
}

///|
/// The values of `m` in the content: those of the collection that it gets, with that object, or its own.
fn Document::items(self : Document, m : MemberNode) -> (Array[Item], Int32?) {
  match m.values {
    [Object(id)] if self.objects[id].kind is Got => {
      let items = self.objects[id].members
        .iter()
        .find_first(m => m.target.name == @syntax.items_directive)
      (items.map(m => m.values).unwrap_or([]), Some(id))
    }
    values => (values, None)
  }
}

///|
/// Add the last node of `nodes`, which is balanced, to the tree.
fn Document::add(
  self : Document,
  node : @nodes.XamlNode,
) -> Unit raise Unwritable {
  let index = self.nodes.length() - 1
  match node {
    NamespaceDeclaration(prefix~, namespace_uri~) =>
      self.add_declaration(prefix, namespace_uri, index)
    StartObject(name) => {
      check_type_name(name, index)
      self.add_object(Started, self.named_type(name), index)
    }
    GetObject => self.add_got_object(index)
    StartMember(name) => {
      check_member_name(name, index)
      let definition = self.types.resolve_member(name)
      let name = definition.map(t => t.member_name()).unwrap_or(name)
      if self.open.last() is Some(object) {
        self.objects[object].members.push({
          start: index,
          end: index,
          target: { name, definition, },
          values: [],
        })
      }
    }
    Value(String(text)) => {
      if text_problem(text) is Some(problem) {
        raise Unwritable(index, problem)
      }
      if self.open_member() is Some(target) {
        target.values.push(Text(text, index))
      }
    }
    Value(Null) => {
      let type_ = self.named_type(@schema.null_extension_type)
      self.add_object(Null, type_, index)
      ignore(self.open.pop())
    }
    Value(_) =>
      raise Unwritable(index, "only text and null can be written as XAML text")
    EndMember => if self.open_member() is Some(target) { target.end = index }
    EndObject => ignore(self.open.pop())
  }
}

///|
/// The last member of the innermost open object.
fn Document::open_member(self : Document) -> MemberNode? {
  self.open.last().bind(object => self.objects[object].members.last())
}

///|
fn Document::add_object(
  self : Document,
  kind : ObjectKind,
  type_ : @syntax.NamedType,
  index : Int32,
) -> Unit {
  let id = self.objects.length()
  if self.open_member() is Some(target) {
    target.values.push(Object(id))
  }
  self.objects.push({
    start: index,
    kind,
    type_,
    declarations: self.declarations.copy(),
    members: [],
  })
  if !self.declarations.is_empty() {
    self.declarations.clear()
    self.prefixes = Map([])
    self.prefix_of = Map([])
  }
  self.open.push(id)
}

///|
fn Document::add_got_object(
  self : Document,
  index : Int32,
) -> Unit raise Unwritable {
  guard self.open_member() is Some(target) else { return }
  let definition = target.target.definition
  let value_type = definition.bind(t => t.value_type)
  let collection = value_type.bind(t => self.types.get_type(t))
  guard definition is Some(found) &&
    (
      found.is_collection_directive() ||
      (collection is Some(t) && (t.is_collection() || t.is_dictionary()))
    ) else {
    raise Unwritable(
      index,
      "the member \{target.target.label()} does not hold a collection or dictionary",
    )
  }
  let name = value_type.unwrap_or(@schema.object_list_type)
  let type_ : @syntax.NamedType = {
    name,
    definition: collection,
    namespace_uri: name.namespace_uri,
  }
  self.add_object(Got, type_, index)
}

///|
/// Add a namespace declaration. `XamlXmlWriter` keeps one prefix for a URI and one URI for a prefix on an
/// element (`XamlXmlWriter.cs:739-754`), and Namespaces in XML 1.0 reserves names.
fn Document::add_declaration(
  self : Document,
  prefix : String,
  namespace_uri : String,
  index : Int32,
) -> Unit raise Unwritable {
  let problem = if prefix != "" && !@nodes.is_ncname(prefix) {
    Some("\{@syntax.quoted(prefix)} is not a namespace prefix")
  } else if prefix == "xml" {
    Some("the prefix \"xml\" cannot be declared")
  } else if @syntax.declaration_problem(prefix, namespace_uri) is Some(problem) {
    Some(problem)
  } else if self.prefixes.contains(prefix) {
    Some(
      "the element already has a declaration of the prefix \{@syntax.quoted(prefix)}",
    )
  } else if self.prefix_of.get(namespace_uri) is Some(other) {
    Some(
      "the namespace \{@syntax.quoted(namespace_uri)} already has the prefix \{@syntax.quoted(other)} on the element",
    )
  } else {
    text_problem(namespace_uri)
  }
  if problem is Some(problem) {
    raise Unwritable(index, problem)
  }
  self.declarations.push((prefix, namespace_uri))
  self.prefixes.set(prefix, ())
  self.prefix_of.set(namespace_uri, prefix)
}

///|
/// The type that `name` names, by its identity, or an unknown type.
fn Document::named_type(
  self : Document,
  name : @nodes.XamlTypeName,
) -> @syntax.NamedType {
  let definition = self.types.get_type(name)
  let name = definition.map(t => t.name).unwrap_or(name)
  { name, definition, namespace_uri: name.namespace_uri, }
}

///|
fn check_type_name(
  name : @nodes.XamlTypeName,
  index : Int32,
) -> Unit raise Unwritable {
  let names = [name]
  while names.pop() is Some(name) {
    check_name(name.name, name.namespace_uri, index)
    for argument in name.type_arguments {
      names.push(argument)
    }
  }
}

///|
fn check_member_name(
  name : @nodes.XamlMemberName,
  index : Int32,
) -> Unit raise Unwritable {
  match name {
    Member(owner~, name~) | Attached(owner~, name~) => {
      check_type_name(owner, index)
      check_name(name, "", index)
    }
    Directive(namespace_uri~, name~)
    | UnknownDirective(namespace_uri~, name~) =>
      check_name(name, namespace_uri, index)
  }
}

///|
fn check_name(
  name : String,
  namespace_uri : String,
  index : Int32,
) -> Unit raise Unwritable {
  if !@nodes.is_ncname(name) {
    raise Unwritable(index, "\{@syntax.quoted(name)} is not an XML name")
  }
  if text_problem(namespace_uri) is Some(problem) {
    raise Unwritable(index, problem)
  }
}

///|
/// Why `text` cannot be in an XML 1.0 document, or `None` when it can.
fn text_problem(text : String) -> String? {
  let length = text.length()
  for offset = 0; offset < length; offset = offset + 1 {
    let unit = text.at(offset).to_int()
    let is_character = unit is (0x9 | 0xA | 0xD) || unit is (0x20..<=0xFFFD)
    let is_paired = if unit is (0xD800..<=0xDBFF) {
      offset + 1 < length && text.at(offset + 1).to_int() is (0xDC00..<=0xDFFF)
    } else if unit is (0xDC00..<=0xDFFF) {
      offset > 0 && text.at(offset - 1).to_int() is (0xD800..<=0xDBFF)
    } else {
      true
    }
    if !is_character || !is_paired {
      let code = "U+\{unit.to_string(radix=16).to_upper()}"
      return Some(
        if is_paired {
          "XML does not allow the character \{code}"
        } else {
          "the text has the surrogate \{code} without the other half of its pair"
        },
      )
    }
  }
  None
}