// How names are spelled. The mode `RoundTrip` uses a spelling only when the lookups of the reader give the
// name back for it, and `SystemXaml` spells names as `XamlXmlWriter` does.

///|
/// A name in the document.
priv enum Spelling {
  /// A name without a prefix that needs no namespace.
  Plain(String)
  /// A name in a namespace. `local_name` gives the name to write in a namespace, or `None` when the
  /// name cannot be written in it.
  Qualified(
    local_name~ : (String) -> String?,
    namespaces~ : UriChoices,
    needs_prefix~ : Bool,
  )
}

///|
/// The namespaces that a document can name something in.
priv struct UriChoices {
  /// Those to declare for it, the first choice first.
  choices : ReadOnlyArray[String]
  /// The choices and then the other ones.
  all : Array[String]
}

///|
/// Where a type name is.
#derive(Eq, Hash)
priv enum TypePlace {
  Element
  /// Before the dot of a member.
  Owner
  Argument
  Braces
}

///|
/// Where the name of a member is.
priv enum MemberPlace {
  Attribute
  NamedArgument
}

///|
/// The range of names that are only looked up.
let no_span : @nodes.SourceSpan = {
  start: { line: 1, column: 1, offset: 0, },
  end: { line: 1, column: 1, offset: 0, },
}

///|
let space_directive : @nodes.XamlMemberName = Directive(
  namespace_uri=@schema.xml_namespace,
  name="space",
)

///|
/// The name of `type_` without the suffix `Extension` of a markup extension, as
/// `XamlXmlWriter.GetTypeName` gives it.
fn short_name(type_ : @syntax.NamedType) -> String {
  let name = type_.name.name
  if type_.definition is Some(definition) &&
    definition.is_markup_extension() &&
    name.has_suffix("Extension") {
    name[:name.length() - "Extension".length()].to_owned()
  } else {
    name
  }
}

///|
/// The type that `name` names in `namespace_uri`, when it is `type_`. The result has the namespace.
fn Writing::type_back(
  self : Writing,
  type_ : @syntax.NamedType,
  namespace_uri : String,
  name : String,
  place : TypePlace,
) -> @syntax.NamedType? {
  let arguments = type_.name.type_arguments.iter().collect()
  let found = try {
    if place is Braces {
      self.names.type_in_braces_of(namespace_uri, name, arguments, no_span)
    } else {
      self.names.type_of(namespace_uri, name, arguments, no_span)
    }
  } catch {
    _ => return None
  }
  if found.name == type_.name {
    Some(found)
  } else {
    None
  }
}

///|
/// The name of `type_` in `namespace_uri`, or `None` when the type cannot be named there.
fn Writing::type_name_in(
  self : Writing,
  type_ : @syntax.NamedType,
  namespace_uri : String,
  place : TypePlace,
) -> String? {
  let key = (type_.name, namespace_uri, place)
  if self.type_names.get(key) is Some(name) {
    return name
  }
  let name = if self.mode is SystemXaml {
    // The namespaces of the type decide, and the suffix goes even when the short name is another type.
    let full_name = type_.name.name
    self
    .type_back(type_, namespace_uri, full_name, Owner)
    .map(_ => short_name(type_))
  } else {
    [short_name(type_), type_.name.name]
    .iter()
    .find_first(name => {
      name != "" &&
      !(place is Element && self.is_other_element(namespace_uri, name)) &&
      self.type_back(type_, namespace_uri, name, place) is Some(_)
    })
  }
  self.type_names.set(key, name)
  name
}

///|
/// Whether an element `name` in `namespace_uri` is not read as an object.
fn Writing::is_other_element(
  self : Writing,
  namespace_uri : String,
  name : String,
) -> Bool {
  name.contains(".") ||
  self.document.types.context.directive(namespace_uri, name) is Some(_) ||
  (name == "XData" && @syntax.is_language_namespace(namespace_uri))
}

///|
fn Writing::type_spelling(
  self : Writing,
  type_ : @syntax.NamedType,
  place : TypePlace,
) -> Spelling {
  Qualified(
    local_name=namespace_uri => self.type_name_in(type_, namespace_uri, place),
    namespaces=self.type_namespaces(type_),
    needs_prefix=false,
  )
}

///|
fn Writing::type_namespaces(
  self : Writing,
  type_ : @syntax.NamedType,
) -> UriChoices {
  if type_.definition is Some(definition) && !definition.namespaces.is_empty() {
    return UriChoices::new(definition.namespaces)
  }
  let { namespace_uri, name, .. } = type_.name
  let namespaces = UriChoices::new([namespace_uri])
  let arity = type_.name.arity()
  if arity > 0 {
    // With an unknown type argument the type is unknown, but the registered type can be in more namespaces.
    for name in [name, name + "Extension"] {
      if self.document.types.context.lookup_type(namespace_uri, name, arity~)
        is Some(open) {
        namespaces.add(UriChoices::new(open.namespaces).all)
      }
    }
  }
  namespaces
}

///|
/// `choices`, and the other URIs that documents can name one of them with: that of the other version of the XAML
/// language, and `using:N` for `clr-namespace:N;assembly=A`.
fn UriChoices::new(choices : ReadOnlyArray[String]) -> UriChoices {
  let namespaces = { choices, all: choices.iter().collect(), }
  for uri in choices {
    if uri == @nodes.xaml_language_namespace {
      namespaces.add([@schema.xaml_language_namespace_2009])
    } else if uri == @schema.xaml_language_namespace_2009 {
      namespaces.add([@nodes.xaml_language_namespace])
    } else if uri.strip_prefix("clr-namespace:") is Some(name) &&
      name.find(";") is Some(end) {
      namespaces.add(["using:\{name[:end]}"])
    }
  }
  namespaces
}

///|
fn UriChoices::add(self : UriChoices, uris : Array[String]) -> Unit {
  for uri in uris {
    if !self.all.contains(uri) {
      self.all.push(uri)
    }
  }
}

///|
/// The spelling of the element of `object`. It has a prefix when the element would declare the default namespace for a
/// directive, which cannot use it.
fn Writing::element_spelling(self : Writing, object : ObjectNode) -> Spelling {
  let spelling = self.fitting_spelling(object)
  guard self.mode is RoundTrip &&
    self.lookup(spelling) is None &&
    spelling is Qualified(local_name~, namespaces~, ..) &&
    namespaces.choices.iter().find_first(uri => local_name(uri) is Some(_))
    is Some(namespace_uri) &&
    self.has_directive_in(object, namespace_uri) else {
    return spelling
  }
  Qualified(local_name~, namespaces~, needs_prefix=true)
}

///|
/// Whether the start tag of `object` can have the name of a directive in `namespace_uri`, also in braces.
fn Writing::has_directive_in(
  self : Writing,
  object : ObjectNode,
  namespace_uri : String,
) -> Bool {
  let is_language = @syntax.is_language_namespace(namespace_uri)
  if is_language && object.type_.name.arity() > 0 {
    return true
  }
  // Most documents have few of these namespaces, and an element in the content finds the declaration.
  if !UriChoices::new([namespace_uri]).all
    .iter()
    .any(uri => self.directive_namespaces.contains(uri)) {
    return false
  }
  let pending = [object]
  while pending.pop() is Some(object) {
    for m in object.members {
      if m.target.name
        is (Directive(namespace_uri=uri, ..)
        | UnknownDirective(namespace_uri=uri, ..)) &&
        !is_implicit(m.target) &&
        (
          uri == namespace_uri ||
          (is_language && @syntax.is_language_namespace(uri))
        ) {
        return true
      }
      for item in m.values {
        if item is Object(child) && self.braces[child] != NoBraces {
          pending.push(self.document.objects[child])
        }
      }
    }
  }
  false
}

///|
/// The spelling of the element of `object`. When it has directives in namespaces of its own, the element
/// needs a namespace in which they are not read as members.
fn Writing::fitting_spelling(self : Writing, object : ObjectNode) -> Spelling {
  let type_ = object.type_
  let directives = if self.mode is SystemXaml {
    []
  } else {
    object.members.filter(m => {
      m.target.name
      is (Directive(namespace_uri~, ..) | UnknownDirective(namespace_uri~, ..)) &&
      namespace_uri != @schema.xml_namespace &&
      namespace_uri != @nodes.xaml_language_namespace
    })
  }
  guard !directives.is_empty() else {
    return self.type_spelling(type_, Element)
  }
  let fits = (namespace_uri : String) => {
    self.type_name_in(type_, namespace_uri, Element) is Some(name) &&
    self.type_back(type_, namespace_uri, name, Element) is Some(element) &&
    directives
    .iter()
    .all(m => self.member_spelling(element, object, m, Attribute) is Some(_))
  }
  let namespaces = self.type_namespaces(type_)
  if !self.has_fitting(namespaces, fits) {
    return self.type_spelling(type_, Element)
  }
  Qualified(
    local_name=namespace_uri => {
      if fits(namespace_uri) {
        self.type_name_in(type_, namespace_uri, Element)
      } else {
        None
      }
    },
    namespaces~,
    needs_prefix=false,
  )
}

///|
/// The spelling of the member `m` of `object` as an attribute or as a named argument in braces, or
/// `None` when it has none. `element` is the type of the object in the namespace of its spelling.
fn Writing::member_spelling(
  self : Writing,
  element : @syntax.NamedType,
  object : ObjectNode,
  m : MemberNode,
  place : MemberPlace,
) -> Spelling? {
  let target = m.target
  let reads_back = (prefix : String, namespace_uri : String, name : String) => {
    let name : @syntax.XmlName = {
      prefix,
      local_name: name,
      namespace_uri,
      span: no_span,
    }
    if name.is_type_arguments() && place is Attribute {
      return false
    }
    let found = try {
      if place is Attribute {
        self.names.attribute_of(element, name)
      } else {
        self.names.named_argument_of(element, name)
      }
    } catch {
      _ => return false
    }
    is_same_member(object, target, found)
  }
  let trusts = self.mode is SystemXaml
  match target.name {
    Attached(owner~, name~) if trusts && place is NamedArgument => {
      // `XamlMarkupExtensionWriter.WriteNonPositionalParameterMember` keeps the suffix of the owner.
      let owner = self.named(owner)
      self.qualified_by(
        uri => {
          self
          .type_name_in(owner, uri, Owner)
          .map(_ => "\{owner.name.name}.\{name}")
        },
        self.type_namespaces(owner),
      )
    }
    Member(owner~, name~) =>
      if trusts || reads_back("", "", name) {
        Some(Plain(name))
      } else {
        self.dotted_spelling(element, object, target, owner, name)
      }
    Attached(owner~, name~) => {
      let is_event = target.definition is Some(found) && found.is_event()
      // `XamlXmlWriter.WriteMemberAsAttribute` writes the owner unless it is the type of the element.
      if owner == element.name && place is Attribute && !(is_event && !trusts) {
        let spelling = self.qualified(
          namespace_uri => {
            self.type_name_in(self.named(owner), namespace_uri, Owner)
            is Some(_) &&
            (trusts || reads_back("p", namespace_uri, name))
          },
          name,
          self.type_namespaces(self.named(owner)),
          needs_prefix=false,
        )
        if spelling is Some(_) {
          return spelling
        }
      }
      self.dotted_spelling(element, object, target, owner, name)
    }
    Directive(namespace_uri~, name~)
    | UnknownDirective(namespace_uri~, name~) =>
      self.qualified(
        uri => {
          if trusts {
            uri == namespace_uri ||
            (
              @syntax.is_language_namespace(uri) &&
              @syntax.is_language_namespace(namespace_uri)
            )
          } else {
            uri != "" && reads_back("p", uri, name)
          }
        },
        name,
        UriChoices::new([namespace_uri]),
        needs_prefix=!trusts,
      )
  }
}

///|
/// The spelling of the element of the member `m` of `object`, or `None` when the member cannot be one.
fn Writing::tag_spelling(
  self : Writing,
  element : @syntax.NamedType,
  object : ObjectNode,
  m : MemberNode,
) -> Spelling? {
  let target = m.target
  match target.name {
    Member(owner~, name~) => {
      // `XamlXmlWriter.WriteMemberAsElement` writes the type of the element, not the owner.
      let own = self.qualified_by(
        uri => {
          self
          .type_name_in(element, uri, Owner)
          .map(type_name => "\{type_name}.\{name}")
          .filter(local_name => {
            self.reads_as(element, object, target, uri, local_name)
          })
        },
        self.type_namespaces(element),
      )
      match own {
        Some(_) => own
        None => self.dotted_spelling(element, object, target, owner, name)
      }
    }
    Attached(owner~, name~) =>
      self.dotted_spelling(element, object, target, owner, name)
    Directive(namespace_uri~, name~)
    | UnknownDirective(namespace_uri~, name~) =>
      self.qualified(
        uri => {
          if self.mode is SystemXaml {
            uri == namespace_uri ||
            (
              @syntax.is_language_namespace(uri) &&
              @syntax.is_language_namespace(namespace_uri)
            )
          } else {
            target.definition is Some(definition) &&
            definition.allowed_locations.element &&
            self.document.types.context.directive(uri, name) is Some(found) &&
            found.member_name() == target.name
          }
        },
        name,
        UriChoices::new([namespace_uri]),
        needs_prefix=false,
      )
  }
}

///|
/// The spelling `Owner.name` of `target`.
fn Writing::dotted_spelling(
  self : Writing,
  element : @syntax.NamedType,
  object : ObjectNode,
  target : @syntax.NamedMember,
  owner : @nodes.XamlTypeName,
  name : String,
) -> Spelling? {
  let owner = self.named(owner)
  self.qualified_by(
    uri => {
      self
      .type_name_in(owner, uri, Owner)
      .map(type_name => "\{type_name}.\{name}")
      .filter(local_name => {
        self.reads_as(element, object, target, uri, local_name)
      })
    },
    self.type_namespaces(owner),
  )
}

///|
/// Whether `local_name`, which has a dot, is read as `target` on `object`.
fn Writing::reads_as(
  self : Writing,
  element : @syntax.NamedType,
  object : ObjectNode,
  target : @syntax.NamedMember,
  namespace_uri : String,
  local_name : String,
) -> Bool {
  if self.mode is SystemXaml {
    return true
  }
  let found = self.names.dotted_member(element, {
    prefix: "",
    local_name,
    namespace_uri,
    span: no_span,
  }) catch {
    _ => return false
  }
  is_same_member(object, target, found)
}

///|
/// Whether a spelling that is read as `found` can stand for `target` on `object`: for the same member, or
/// for an attached event when it gives the event that is paired with it and that the object does not set.
fn is_same_member(
  object : ObjectNode,
  target : @syntax.NamedMember,
  found : @syntax.NamedMember,
) -> Bool {
  if found.name == target.name {
    return true
  }
  target.name is Attached(..) &&
  target.definition is Some(definition) &&
  definition.paired_event() is Some(event) &&
  event.member_name() == found.name &&
  !object.members.iter().any(m => m.target.name == found.name)
}

///|
fn Writing::named(
  self : Writing,
  name : @nodes.XamlTypeName,
) -> @syntax.NamedType {
  self.document.named_type(name)
}

///|
/// The spelling `local_name` in the namespaces that `fits` accepts, or `None` when there is none.
fn Writing::qualified(
  self : Writing,
  fits : (String) -> Bool,
  local_name : String,
  namespaces : UriChoices,
  needs_prefix~ : Bool,
) -> Spelling? {
  if !self.has_fitting(namespaces, fits) {
    return None
  }
  Some(
    Qualified(
      local_name=uri => if fits(uri) { Some(local_name) } else { None },
      namespaces~,
      needs_prefix~,
    ),
  )
}

///|
/// The spelling that `local_name` gives, or `None` when no namespace has one.
fn Writing::qualified_by(
  self : Writing,
  local_name : (String) -> String?,
  namespaces : UriChoices,
) -> Spelling? {
  let fits = (uri : String) => local_name(uri) is Some(_)
  if self.has_fitting(namespaces, fits) {
    Some(Qualified(local_name~, namespaces~, needs_prefix=false))
  } else {
    None
  }
}

///|
/// Whether one of the choices fits, or another of `namespaces` that is declared in scope.
fn Writing::has_fitting(
  self : Writing,
  namespaces : UriChoices,
  fits : (String) -> Bool,
) -> Bool {
  namespaces.choices.iter().any(fits) ||
  namespaces.all
  .iter()
  .any(uri => self.output.namespaces.get(uri) is Some([_, ..]) && fits(uri))
}

///|
/// `spelling` with the prefix of the nearest element that declares a namespace for it, and whether an inner
/// declaration hides that prefix. `None` when no element has one. As in `XamlXmlWriter.LookupPrefix`, the
/// first of the namespaces comes first on an element.
fn Writing::lookup(self : Writing, spelling : Spelling) -> (String, Bool)? {
  guard spelling is Qualified(local_name~, namespaces~, needs_prefix~) else {
    guard spelling is Plain(name) else { None }
    return Some((name, false))
  }
  let output = self.output
  let mut found : (Int32, String)? = None
  // The choices come before the others, of which the last declaration is found.
  let mut best = (-1, 0, -1)
  for rank, namespace_uri in namespaces.all {
    guard output.namespaces.get(namespace_uri) is Some(places) &&
      places
      .rev_iter()
      .find_first(place => {
        !(needs_prefix && output.declared[place].prefix == "") &&
        !(self.mode is RoundTrip && output.is_shadowed(place))
      })
      is Some(place) else {
      continue
    }
    let { depth, .. } = output.declared[place]
    let order = (depth, -Int32::min(rank, namespaces.choices.length()), place)
    if order > best && local_name(namespace_uri) is Some(name) {
      best = order
      found = Some((place, name))
    }
  }
  guard found is Some((place, name)) else { None }
  Some(
    (
      qualified_name(output.declared[place].prefix, name),
      output.is_shadowed(place),
    ),
  )
}

///|
/// Write `spelling` with a prefix in scope, or with one that it declares on the open start tag for the
/// node `index`. `label` names the node in an error.
fn Writing::spell(
  self : Writing,
  spelling : Spelling,
  index : Int32,
  label : String,
) -> String raise Unwritable {
  let output = self.output
  // `XamlXmlWriter.FindPrefix` does not look for an outer declaration when the nearest one is shadowed.
  if self.lookup(spelling) is Some((name, false)) {
    if output.tag is Some(tag) &&
      spelling is Qualified(..) &&
      !name.contains(":") {
      tag.uses_default = true
    }
    return self.checked_name(name, index, label)
  }
  guard spelling is Qualified(local_name~, namespaces~, needs_prefix~) else {
    ""
  }
  for namespace_uri in namespaces.choices {
    guard local_name(namespace_uri) is Some(name) else { continue }
    if output.is_innermost(output.namespaces.get(namespace_uri)) {
      raise Unwritable(
        index,
        "\{label} needs a prefix for the namespace \{@syntax.quoted(namespace_uri)}, which its element declares without one",
      )
    }
    // Only a name without a prefix has no namespace.
    if namespace_uri == "" &&
      output.tag is Some(tag) &&
      (tag.uses_default || output.is_innermost(output.places.get(""))) {
      raise Unwritable(
        index,
        "\{label} has no namespace, and its element needs a default namespace",
      )
    }
    let prefix = self.new_prefix(namespace_uri, needs_prefix~)
    output.declare_prefix(prefix, namespace_uri)
    return self.checked_name(qualified_name(prefix, name), index, label)
  }
  raise Unwritable(index, "no name in the document is read as \{label}")
}

///|
/// `name`, unless the mode `SystemXaml` dropped a suffix that is the whole name of the type `label`.
fn Writing::checked_name(
  self : Writing,
  name : String,
  index : Int32,
  label : String,
) -> String raise Unwritable {
  let start = name.find(":").map(colon => colon + 1).unwrap_or(0)
  if self.mode is SystemXaml && !@nodes.is_ncname(name[start:].to_owned()) {
    raise Unwritable(
      index,
      "\{label} has no XML name without the suffix Extension",
    )
  }
  name
}

///|
fn qualified_name(prefix : String, local_name : String) -> String {
  if prefix == "" {
    local_name
  } else {
    "\{prefix}:\{local_name}"
  }
}

///|
/// The prefix to declare for `namespace_uri`, as `XamlXmlWriter.DefinePrefix` chooses it.
fn Writing::new_prefix(
  self : Writing,
  namespace_uri : String,
  needs_prefix~ : Bool,
) -> String {
  let output = self.output
  if namespace_uri == "" || (!needs_prefix && output.is_free("", namespace_uri)) {
    return ""
  }
  match self.document.types.context.preferred_prefix(namespace_uri) {
    Some(preferred) if !needs_prefix || output.is_free(preferred, namespace_uri) =>
      output.free_prefix(preferred, namespace_uri)
    _ => output.free_prefix("p", namespace_uri)
  }
}