///|
pub(all) struct InlineResult {
  inlines : Array[Inline]
  diagnostics : Array[Diagnostic]
  end_font : Font
  previous_font : Font
  continues : Bool
} derive(Eq, Debug)

///|
pub extend InlineResult with Eq::{equal, not_equal}

///|
pub extend InlineResult with @debug.Debug::{to_repr}

///|
fn font_named(name : String) -> Font? {
  match name {
    "R" | "1" => Some(Roman)
    "B" | "3" => Some(Bold)
    "I" | "2" => Some(Italic)
    "CW" | "CR" | "C" | "4" => Some(Code)
    _ => None
  }
}

///|
/// Read a one-character, two-character, or bracketed escape parameter.
fn escape_parameter(chars : Array[Char], at : Int32) -> (String, Int32, Bool) {
  if at >= chars.length() {
    return ("", at, false)
  }
  if chars[at] == '[' {
    let mut end = at + 1
    while end < chars.length() && chars[end] != ']' {
      end = end + 1
    }
    if end == chars.length() {
      (chars_string(chars, at + 1, end), end, false)
    } else {
      (chars_string(chars, at + 1, end), end + 1, true)
    }
  } else if chars[at] == '(' {
    if at + 2 < chars.length() {
      (chars_string(chars, at + 1, at + 3), at + 3, true)
    } else {
      (chars_string(chars, at + 1, chars.length()), chars.length(), false)
    }
  } else {
    (chars[at].to_string(), at + 1, true)
  }
}

///|
/// Decode a bounded line of roff text. No string/register interpolation occurs.
pub fn decode_inline(
  text : String,
  line~ : Int32 = 1,
  initial_font~ : Font = Roman,
  previous_font~ : Font = Roman,
  max_chars~ : Int32 = 16000,
) -> Result[InlineResult, Diagnostic] {
  if max_chars <= 0 {
    return Err(
      diagnostic(
        "invalid-options",
        "max_chars must be positive",
        line,
        severity=Error,
      ),
    )
  }
  let mut count = 0
  for _ in text.iter() {
    count = count + 1
    if count > max_chars {
      return Err(
        diagnostic(
          "inline-limit",
          "Inline source exceeds max_chars",
          line,
          severity=Error,
        ),
      )
    }
  }
  let chars = text.to_array()
  let inlines : Array[Inline] = []
  let diagnostics : Array[Diagnostic] = []
  let out = StringBuilder()
  let mut font = initial_font
  let mut previous = previous_font
  let mut continues = false
  let mut i = 0
  while i < chars.length() {
    let c = chars[i]
    if c != '\\' {
      if c.is_control() && c != '\t' {
        diagnostics.push(
          diagnostic("control-character", "Control character removed", line),
        )
      } else {
        out.write_char(c)
      }
      i = i + 1
      continue
    }
    if i + 1 >= chars.length() {
      diagnostics.push(
        diagnostic("trailing-escape", "Trailing backslash has no operand", line),
      )
      out.write_char('\\')
      break
    }
    let code = chars[i + 1]
    i = i + 2
    match code {
      '\\' | 'e' => out.write_char('\\')
      '-' => out.write_char('-')
      ' ' => out.write_char(' ')
      '~' => out.write_char('\u{00a0}')
      't' => out.write_char('\t')
      '&' | '%' | '/' | ',' | ':' => ()
      'c' => continues = true
      '"' | '#' => break
      'f' => {
        let (name, next, complete) = escape_parameter(chars, i)
        i = next
        if !complete {
          diagnostics.push(
            diagnostic("incomplete-font", "Incomplete font escape", line),
          )
        }
        let next_font = if name == "P" || name == "" {
          Some(previous)
        } else {
          font_named(name)
        }
        match next_font {
          Some(value) => {
            if !out.is_empty() {
              inlines.push(Inline::text(out.to_string(), font~))
              out.reset()
            }
            previous = font
            font = value
          }
          None =>
            diagnostics.push(
              diagnostic("unknown-font", "Unsupported font: " + name, line),
            )
        }
      }
      's' => {
        if i < chars.length() && (chars[i] == '+' || chars[i] == '-') {
          i = i + 1
        }
        let (_, next, complete) = escape_parameter(chars, i)
        i = next
        if !complete {
          diagnostics.push(
            diagnostic("incomplete-size", "Incomplete size escape", line),
          )
        }
      }
      '(' | '[' => {
        let (name, next, complete) = escape_parameter(chars, i - 1)
        i = next
        if !complete {
          diagnostics.push(
            diagnostic(
              "incomplete-glyph", "Incomplete named glyph escape", line,
            ),
          )
        }
        match named_glyph(name) {
          Some(value) => out.write_string(value)
          None => {
            out.write_string("\\[" + name + "]")
            diagnostics.push(
              diagnostic("unknown-glyph", "Unknown named glyph: " + name, line),
            )
          }
        }
      }
      '*' | 'n' => {
        let (name, next, _) = escape_parameter(chars, i)
        i = next
        diagnostics.push(
          diagnostic(
            "unsupported-interpolation",
            "String/register interpolation is not evaluated: " + name,
            line,
          ),
        )
      }
      _ => {
        out.write_char('\\')
        out.write_char(code)
        diagnostics.push(
          diagnostic(
            "unknown-escape",
            "Escape is preserved literally: " + code.to_string(),
            line,
          ),
        )
      }
    }
  }
  if !out.is_empty() {
    inlines.push(Inline::text(out.to_string(), font~))
  }
  Ok({
    inlines,
    diagnostics,
    end_font: font,
    previous_font: previous,
    continues,
  })
}