// Markup extensions in attribute values (design D13).

///|
/// Find out how each object can be written in braces, and in the mode `RoundTrip` whether an element with the
/// same nodes exists for those that can.
fn Writing::check_braces(self : Writing) -> Unit {
  // The objects in an object have higher numbers, so they come first.
  for id in self.document.objects.length()>..0 {
    let object = self.document.objects[id]
    if self.mode is SystemXaml {
      self.braces[id] = self.system_xaml_braces(object)
      continue
    }
    self.braces[id] = self.braces_form(object)
    if self.braces[id] != NoBraces {
      self.keeps_nodes[id] = !object.members.iter().any(is_positional) &&
        (try self.trial(id, object.type_, false, _ => false).place() catch {
          _ => false
        } noraise {
          _ => true
        })
    }
  }
}

///|
fn is_positional(m : MemberNode) -> Bool {
  m.target.name == @syntax.positional_parameters_directive
}

///|
fn Writing::braces_form(self : Writing, object : ObjectNode) -> BracesForm {
  let type_ = object.type_
  let can_be_named = self.has_fitting(self.type_namespaces(type_), uri => {
    self.type_name_in(type_, uri, Braces) is Some(_)
  })
  if object.kind is Got || !object.declarations.is_empty() || !can_be_named {
    return NoBraces
  }
  let mut form = if type_.definition is Some(definition) &&
    definition.is_markup_extension() &&
    type_.name.arity() == 0 {
    Usual
  } else {
    Readable
  }
  for index, m in object.members {
    let is_readable = if is_positional(m) {
      index == 0 && !m.values.is_empty()
    } else {
      m.values.length() == 1 &&
      !is_implicit(m.target) &&
      self.member_spelling(type_, object, m, NamedArgument) is Some(_)
    }
    guard is_readable else { return NoBraces }
    if m.target.definition is Some(definition) &&
      definition.is_collection_directive() &&
      !is_positional(m) {
      form = Readable
    }
    for item in m.values {
      guard item is Object(child) else { continue }
      match self.braces[child] {
        NoBraces => return NoBraces
        Readable => form = Readable
        Usual => ()
      }
    }
  }
  form
}

///|
/// An extension in braces that is written up to some member and value.
priv struct OpenBraces {
  object : ObjectNode
  /// The type in the namespace of its name.
  type_ : @syntax.NamedType
  parameters : Array[ReadOnlyArray[(Char, Char)]]
  mut member_index : Int32
  mut value_index : Int32
  /// What comes before the next argument.
  mut separator : String
}

///|
/// The attribute value for `item`, of which `name_of` writes the names.
fn Writing::attribute_text(
  self : Writing,
  item : Item,
  name_of : (Spelling, Int32, String) -> String raise Unwritable,
) -> String raise Unwritable {
  let root = match item {
    Text(text, _) =>
      return if text.has_prefix("{") { "{}\{text}" } else { text }
    Object(id) => id
  }
  let output = StringBuilder()
  let open = [self.open_braces(root, output, name_of)]
  while open.last() is Some(braces) {
    let members = braces.object.members
    guard members.get(braces.member_index) is Some(m) else {
      output.write_char('}')
      ignore(open.pop())
      continue
    }
    guard m.values.get(braces.value_index) is Some(item) else {
      braces.member_index += 1
      braces.value_index = 0
      continue
    }
    output.write_string(braces.separator)
    braces.separator = ", "
    let pairs = if is_positional(m) {
      @syntax.positional_pairs(braces.parameters, braces.value_index)
    } else {
      let name = match
        self.member_spelling(braces.type_, braces.object, m, NamedArgument) {
        Some(spelling) => name_of(spelling, m.start, m.target.label())
        None => m.target.name.name()
      }
      output.write_string("\{name}=")
      braces.type_.bracket_pairs(name)
    }
    braces.value_index += 1
    match item {
      Text(text, _) => output.write_string(self.argument_text(text, pairs))
      Object(id) => open.push(self.open_braces(id, output, name_of))
    }
  }
  output.to_string()
}

///|
fn Writing::open_braces(
  self : Writing,
  id : Int32,
  output : StringBuilder,
  name_of : (Spelling, Int32, String) -> String raise Unwritable,
) -> OpenBraces raise Unwritable {
  let object = self.document.objects[id]
  let type_ = object.type_
  let is_system_generic = self.mode is SystemXaml && type_.name.arity() > 0
  let type_name_of = (spelling : Spelling, index : Int32, label : String) => {
    if is_system_generic && self.lookup(spelling) is Some((_, true)) {
      // `XamlXmlWriter.WriteTypeArguments` would declare a new prefix, which braces cannot.
      raise Unwritable(index, "\{label} has no prefix in scope")
    }
    name_of(spelling, index, label)
  }
  let name = type_name_of(
    self.type_spelling(type_, Braces),
    object.start,
    type_.name.name,
  )
  let arguments = self.type_arguments_text(type_, object.start, type_name_of)
  output.write_char('{')
  if is_system_generic {
    // `XamlXmlWriter.WriteTypeArguments` writes the directive as the first argument.
    let directive = name_of(
      self.type_arguments_spelling(),
      object.start,
      "TypeArguments",
    )
    let text = self.argument_text(arguments, [])
    output.write_string("\{name} \{directive}=\{text}")
    return {
      object,
      type_,
      parameters: [],
      member_index: 0,
      value_index: 0,
      separator: ", ",
    }
  }
  let name = if arguments == "" { name } else { "\{name}(\{arguments})" }
  output.write_string(
    if name.contains(",") || name.contains(" ") {
      "\"\{name}\""
    } else {
      name
    },
  )
  {
    object,
    type_,
    parameters: type_.parameter_pairs(),
    member_index: 0,
    value_index: 0,
    separator: " ",
  }
}

///|
/// `text` as an argument, in quotation marks when it has a character that can end or change it. `pairs` are
/// the brackets that hide such characters in the argument.
fn Writing::argument_text(
  self : Writing,
  text : String,
  pairs : ReadOnlyArray[(Char, Char)],
) -> String {
  let keeps_text = self.mode is RoundTrip
  let is_special = (character : Char) => {
    character is ('\'' | '"' | ',' | '=' | '{' | '}' | '\\' | ' ') ||
    (
      keeps_text &&
      (
        character is ('\t' | '\n' | '\r' | '\u{0C}') ||
        pairs.iter().any(pair => pair.0 == character || pair.1 == character)
      )
    )
  }
  if text != "" && !text.iter().any(is_special) {
    return text
  }
  let output = StringBuilder()
  output.write_char('"')
  if keeps_text && text.has_prefix("{") {
    output.write_string("{}")
  }
  for character in text {
    if character is ('\\' | '"') {
      output.write_char('\\')
    }
    output.write_char(character)
  }
  output.write_char('"')
  output.to_string()
}

///|
/// A type name in type arguments that is written up to some argument.
priv struct OpenTypeName {
  type_ : @syntax.NamedType
  mut index : Int32
}

///|
/// The type arguments of `type_` as `prefix:Name(Arg), prefix:Name`.
fn Writing::type_arguments_text(
  self : Writing,
  type_ : @syntax.NamedType,
  index : Int32,
  name_of : (Spelling, Int32, String) -> String raise Unwritable,
) -> String raise Unwritable {
  let output = StringBuilder()
  let open = [{ type_, index: 0, }]
  while open.last() is Some(outer) {
    let arguments = outer.type_.name.type_arguments
    guard arguments.get(outer.index) is Some(argument) else {
      ignore(open.pop())
      if !arguments.is_empty() && !open.is_empty() {
        output.write_char(')')
      }
      continue
    }
    if outer.index > 0 {
      output.write_string(", ")
    }
    outer.index += 1
    let argument = self.named(argument)
    output.write_string(
      name_of(self.type_spelling(argument, Argument), index, argument.name.name),
    )
    if argument.name.arity() > 0 {
      output.write_char('(')
    }
    open.push({ type_: argument, index: 0, })
  }
  output.to_string()
}