///|
/// Read a path in the syntax of WPF's `PropertyPath`:
///
/// - `Child.Width` are properties.
/// - `(Grid.Row)` or `(local:Grid.Row)` is a member of an owner type, which `resolver` finds.
/// - `Items[0]` and `Cells[1,(sys:Int32)2]` are indexers with their arguments. `^` before a character makes it a part of the
///   argument.
///
/// The empty text and `.` are the source itself. The path works with the types and objects of `registry`. One without owner types
/// and types of arguments needs no `resolver`.
pub fn parse(
  text : String,
  resolver~ : PathResolver = PathResolver::new(),
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> PropertyPath raise PathParseError {
  let parser = { text, resolver, registry, types: type_table(registry), }
  let segments = []
  let ranges = []
  let mut at = skip_space(text, 0)
  // A dot before the first segment means nothing.
  if text.get(at) is Some('.') {
    at = skip_space(text, at + 1)
  }
  while at < text.length() {
    let (segment, end) = parser.segment(at)
    segments.push(segment)
    ranges.push((at, end))
    at = skip_space(text, end)
    match text.get(at) {
      Some('.') => {
        at = skip_space(text, at + 1)
        if at == text.length() {
          raise empty_segment(at)
        }
      }
      // `segment` reports `/`.
      None | Some('[' | '/') => ()
      Some(_) => raise unexpected(text, at)
    }
  }
  {
    registry,
    types: parser.types,
    segments: ReadOnlyArray::from_array(segments),
    ranges: ReadOnlyArray::from_array(ranges),
  }
}

///|
priv struct Parser {
  text : String
  resolver : PathResolver
  registry : @dependency.PropertyRegistry
  types : TypeTable
}

///|
/// The segment that starts at `start`, and where it ends.
fn Parser::segment(
  self : Parser,
  start : Int32,
) -> (PathSegment, Int32) raise PathParseError {
  match self.text.at(start) {
    '[' => self.indexer(start)
    '.' => raise empty_segment(start)
    '/' => raise unsupported("`/`, the current item,", start, start + 1)
    '#' => raise unsupported("`#` at the start of a segment", start, start + 1)
    _ => self.property(start)
  }
}

///|
/// Where the name that starts at `start` ends, and how many parentheses are open there. In parentheses, all characters are a part of
/// the name.
fn scan_name(text : String, start : Int32) -> (Int32, Int32) {
  let mut level = 0
  for at in start.. level += 1
      ')' => level -= 1
      '.' | '/' | '[' | ']' if level <= 0 => return (at, level)
      _ => ()
    }
  }
  (text.length(), level)
}

///|
/// Whether the parser reads `name` without more parentheses as the property with this name.
fn is_bare_name(name : String) -> Bool {
  let all = (0, name.length())
  scan_name(name, 0) == (name.length(), 0) &&
  trimmed_range(name, 0, name.length()) == all &&
  !(name is ("" | ['#', ..] | ['(', .., ')']))
}

///|
/// A name, or a name or a member of an owner type in parentheses.
fn Parser::property(
  self : Parser,
  start : Int32,
) -> (PathSegment, Int32) raise PathParseError {
  let text = self.text
  let (end, level) = scan_name(text, start)
  if level != 0 {
    raise PathParseError(
      code=UnmatchedParenthesis,
      message="a parenthesis has no match",
      start~,
      end~,
    )
  }
  if end == start {
    raise unexpected(text, start)
  }
  let (_, end) = trimmed_range(text, start, end)
  guard text[start:end] is ['(', .. inner, ')'] else {
    return (Property(text[start:end].to_owned()), end)
  }
  if parse_int(inner) is Some(_) {
    raise unsupported("`(\{inner})`, a path parameter,", start, end)
  }
  let segment = match inner.rev_find(".") {
    Some(dot) => self.qualified(start + 1, start + 1 + dot, end - 1)
    // As in WPF, the name can be empty and can have white space around it.
    None => Property(inner.to_owned())
  }
  (segment, end)
}

///|
/// The member of an owner type from `start` to `end`, whose last dot is at `dot`.
fn Parser::qualified(
  self : Parser,
  start : Int32,
  dot : Int32,
  end : Int32,
) -> PathSegment raise PathParseError {
  let { text, registry, .. } = self
  let (start, owner_end) = trimmed_range(text, start, dot)
  let (name_start, end) = trimmed_range(text, dot + 1, end)
  let written = text[start:owner_end].to_owned()
  let name = text[name_start:end].to_owned()
  let (prefix, owner_name) = split_type(written, start, owner_end)
  let owner = (self.resolver.owner)(prefix, owner_name) catch {
    UnknownPrefix => raise unknown_prefix(prefix, start, owner_end)
    UnknownType =>
      raise PathParseError(
        code=UnknownOwner,
        message="there is no owner type `\{written}`",
        start~,
        end~,
      )
  }
  let property = @dependency.lookup_property(owner, name, registry~) catch {
    error =>
      raise PathParseError(
        code=RegistryMismatch,
        message=error.to_string(),
        start~,
        end~,
      )
  }
  let found = match property {
    Some(property) => Dependency(property)
    None =>
      match self.types.find(owner, Some(name)) {
        Some((owner, _)) => Registered(owner, name)
        None =>
          raise PathParseError(
            code=UnknownProperty,
            message="there is no property `\{written}.\{name}`",
            start~,
            end~,
          )
      }
  }
  Qualified(found, written~)
}

///|
/// The prefix and the name of the type `written`, which is from `start` to `end`.
fn split_type(
  written : String,
  start : Int32,
  end : Int32,
) -> (String?, String) raise PathParseError {
  if written.contains_any(chars="()") {
    raise unsupported("`\{written}`, a generic type,", start, end)
  }
  match written.split_once(":") {
    Some((prefix, name)) => (Some(prefix.to_owned()), name.to_owned())
    None => (None, written)
  }
}

///|
/// The indexer whose `[` is at `open`.
fn Parser::indexer(
  self : Parser,
  open : Int32,
) -> (PathSegment, Int32) raise PathParseError {
  let text = self.text
  let arguments = []
  for at = open + 1 {
    let start = skip_space(text, at)
    let (type_name, type_end) = if text.get(start) is Some('(') {
      self.argument_type(open, start + 1)
    } else {
      ("", start)
    }
    let (value, end) = self.argument_value(
      open,
      if type_end > start {
        type_end + 1
      } else {
        start
      },
    )
    if text.at(end) == ',' {
      arguments.push(self.argument(type_name, value, start, type_end, end))
      continue end + 1
    }
    let all = text[open + 1:end]
    if all.is_empty() {
      raise PathParseError(
        code=EmptyIndexer,
        message="an indexer needs an argument",
        start=open,
        end=end + 1,
      )
    }
    arguments.push(
      if all.has_prefix("()") &&
        !all.any(c => c is ('^' | '[' | ',') || c.is_whitespace()) {
        // Avalonia and MAUI agree on this text, and WPF leaves out the `()`.
        Text(all.to_owned())
      } else {
        self.argument(type_name, value, start, type_end, end)
      },
    )
    break (Indexer(ReadOnlyArray::from_array(arguments)), end + 1)
  }
}

///|
/// The type that starts at `start`, after its `(`, and where its `)` is.
fn Parser::argument_type(
  self : Parser,
  open : Int32,
  start : Int32,
) -> (String, Int32) raise PathParseError {
  let out = Unescaped::new(self.text, start)
  for at = start {
    match self.unit(open, at) {
      ')' => break (out.finish(at), at)
      '^' => {
        ignore(self.unit(open, at + 1))
        out.skip(at)
        continue at + 2
      }
      _ => continue at + 1
    }
  }
}

///|
/// The value that starts at `start`, and where the `,` or `]` after it is.
///
/// As in WPF, a `[` opens a pair up to the next `]`, in which only `^` means something. White space at the end is left out, also when
/// it was escaped, unless the last character was.
fn Parser::argument_value(
  self : Parser,
  open : Int32,
  start : Int32,
) -> (String, Int32) raise PathParseError {
  let out = Unescaped::new(self.text, start)
  let mut nested = false
  let mut space_last = false
  for at = start {
    let unit = self.unit(open, at)
    match unit {
      '^' => {
        ignore(self.unit(open, at + 1))
        out.skip(at)
        space_last = false
        continue at + 2
      }
      ',' | ']' if !nested => {
        let value = out.finish(at)
        let length = if space_last {
          trimmed_range(value, 0, value.length()).1
        } else {
          value.length()
        }
        break (value[:length].to_owned(), at)
      }
      '[' => nested = true
      ']' => nested = false
      _ => ()
    }
    space_last = !nested && is_space(unit)
    continue at + 1
  }
}

///|
/// The argument from `start` to `end`, with a type in parentheses that ends at `type_end`, and then a value. Each can be empty.
fn Parser::argument(
  self : Parser,
  type_name : String,
  value : String,
  start : Int32,
  type_end : Int32,
  end : Int32,
) -> PathArgument raise PathParseError {
  if type_name.is_empty() {
    return Text(value)
  }
  if value.is_empty() {
    if parse_int(type_name) is Some(_) {
      raise unsupported("`(\{type_name})`, a path parameter,", start, end)
    }
    return Text("(\{type_name})")
  }
  let (prefix, name) = split_type(type_name, start + 1, type_end)
  let found = (self.resolver.argument_type)(prefix, name) catch {
    UnknownPrefix => raise unknown_prefix(prefix, start + 1, type_end)
    UnknownType =>
      raise PathParseError(
        code=UnknownArgumentType,
        message="there is no type `\{type_name}` for an argument",
        start=start + 1,
        end=type_end,
      )
  }
  guard found is Some({ name: type_found, parse, }) else {
    return Text("(\{type_name})\{value}")
  }
  let (from, to) = trimmed_range(value, 0, value.length())
  let text = value[from:to].to_owned()
  let value = parse(text) catch {
    error =>
      raise PathParseError(
        code=ArgumentConversion,
        message="\{@debug.to_string(text)} is no `\{type_name}` value: \{error}",
        start~,
        end~,
      )
  }
  Typed(written=type_name, type_name=type_found, text~, value~)
}

///|
/// The code unit at `at`, in the indexer whose `[` is at `open`.
fn Parser::unit(
  self : Parser,
  open : Int32,
  at : Int32,
) -> UInt16 raise PathParseError {
  guard self.text.get(at) is Some(unit) else {
    raise PathParseError(
      code=UnclosedIndexer,
      message="an indexer has no `]`",
      start=open,
      end=self.text.length(),
    )
  }
  unit
}

///|
/// A part of the text without its escape characters.
priv struct Unescaped {
  text : String
  out : StringBuilder
  /// What comes before this is in `out`.
  mut start : Int32
}

///|
fn Unescaped::new(text : String, start : Int32) -> Unescaped {
  { text, out: StringBuilder(), start, }
}

///|
/// Leave out the character at `at`.
fn Unescaped::skip(self : Unescaped, at : Int32) -> Unit {
  self.out.write_view(self.text[self.start:at])
  self.start = at + 1
}

///|
fn Unescaped::finish(self : Unescaped, end : Int32) -> String {
  self.skip(end)
  self.out.to_string()
}

///|
fn unexpected(text : String, at : Int32) -> PathParseError {
  let character = text.get_char(at).unwrap_or('\u{FFFD}')
  PathParseError(
    code=PathSyntax,
    message="`\{character}` cannot be here",
    start=at,
    end=at + character.utf16_len(),
  )
}

///|
fn empty_segment(at : Int32) -> PathParseError {
  PathParseError(
    code=EmptySegment,
    message="a segment has no name",
    start=at,
    end=at,
  )
}

///|
fn unsupported(what : String, start : Int32, end : Int32) -> PathParseError {
  PathParseError(
    code=UnsupportedSyntax,
    message="\{what} is not supported in a path",
    start~,
    end~,
  )
}

///|
fn unknown_prefix(
  prefix : String?,
  start : Int32,
  end : Int32,
) -> PathParseError {
  PathParseError(
    code=UnknownPrefix,
    message="the prefix `\{prefix.unwrap_or("")}` is not declared",
    start~,
    end~,
  )
}

///|
/// Whether the code unit is white space as in .NET, which is in the basic multilingual plane.
fn is_space(unit : UInt16) -> Bool {
  unit.to_int().unsafe_to_char().is_whitespace()
}

///|
/// The first position from `start` on without white space.
fn skip_space(text : String, start : Int32) -> Int32 {
  let mut at = start
  while at < text.length() && is_space(text.at(at)) {
    at += 1
  }
  at
}

///|
/// The range from `start` to `end` without the white space at both ends. The end comes first, so that white space alone is empty at
/// `start`.
fn trimmed_range(text : String, start : Int32, end : Int32) -> (Int32, Int32) {
  let mut start = start
  let mut end = end
  while start < end && is_space(text.at(end - 1)) {
    end -= 1
  }
  while start < end && is_space(text.at(start)) {
    start += 1
  }
  (start, end)
}

///|
/// The number in `text`, as .NET reads an `Int32` with `NumberStyles.Integer`: digits with a sign, and white space around them.
fn parse_int(text : StringView) -> Int32? {
  let (negative, digits) = match text.trim(chars="\t\n\u{B}\u{C}\r ") {
    ['-', .. rest] => (true, rest)
    ['+', .. rest] | rest => (false, rest)
  }
  if digits.is_empty() {
    return None
  }
  let mut value = 0L
  for digit in digits {
    guard digit is ('0'..<='9') else { return None }
    value = value * 10 + (digit.to_int() - '0').to_int64()
    if value > 2147483648L {
      return None
    }
  }
  let value = if negative { -value } else { value }
  if value > 2147483647L {
    None
  } else {
    Some(value.to_int())
  }
}