///|
/// Why a segment does not work.
pub(all) enum FailureReason {
  /// The type of the value has no such property or indexer.
  UnknownMember
  /// The type of the value is not registered, or the segment needs a dependency object and the value has none.
  CannotStepInto
  /// The value before the segment is null.
  NullValue
  /// The object before the segment belongs to another registry than the path.
  RegistryMismatch
  /// The arguments do not fit the indexer.
  InvalidArgument
  /// The property or the indexer has no setter.
  ReadOnly
  /// The value that is set has another type than the property or the indexer.
  InvalidValue
  /// The getter raised this error.
  Raised(Error)
}

///|
/// The first segment of a path that does not work, and why.
pub struct PathFailure {
  /// The position of the segment in the path.
  segment : Int32
  /// Where the segment starts in the text that was parsed, in UTF-16 code units.
  start : Int32
  /// Where the segment ends in that text.
  end : Int32
  reason : FailureReason
  /// What is wrong, for people. It has the text of the segment.
  message : String
}

///|
/// The message.
pub impl Show for PathFailure with fn output(self, logger) {
  logger.write_string(self.message)
}

///|
pub extend PathFailure with Show::{to_string}

///|
/// The failure of a segment that does not know its place in the path. It never leaves the package.
priv suberror Unresolved {
  Unresolved(FailureReason, String)
}

///|
/// A member of a value, of whatever kind.
priv struct Access {
  get : () -> @dependency.AnyValue raise
  set : (@dependency.AnyValue) -> Unit raise
  /// Calls the function after each change, until the returned function is called.
  subscribe : (() -> Unit raise) -> () -> Unit
}

///|
/// The access to a registered property or indexer.
fn[V] access(
  key : @dependency.ValueKey[V],
  get : () -> V raise,
  set : ((V) -> Unit raise)?,
  subscribe : ((() -> Unit raise) -> () -> Unit)?,
) -> Access {
  {
    get: () => key.wrap(get()),
    set: value => {
      guard set is Some(set) else {
        raise Unresolved(ReadOnly, "it has no setter and is read-only")
      }
      guard key.unwrap(value) is Some(next) else {
        raise Unresolved(
          InvalidValue,
          "it has `\{key.id()}` values, and cannot be set to a `\{value.key_id()}` value",
        )
      }
      set(next)
    },
    subscribe: subscribe.unwrap_or(_ => () => ()),
  }
}

///|
/// The access to a dependency property. The property checks the values that it gets.
fn dependency_access(
  property : @dependency.PropertyInfo,
  object : @dependency.DependencyObject,
) -> Access {
  {
    get: () => property.get_value(object),
    set: value => property.set_value(object, value),
    subscribe: changed => {
      let token = object.add_change_handler((_, changing, _, _) => {
        if changing == property {
          changed()
        }
      })
      () => ignore(object.remove_change_handler(token))
    },
  }
}

///|
/// The member of `value` that `segment` names.
///
/// This looks at the value, at the one inside it, and so on up to a dependency object. A name is a dependency property of the object,
/// or else a registered property of the first of them that has it. An indexer is found in the same way as a registered property.
fn PropertyPath::resolve(
  self : PropertyPath,
  segment : PathSegment,
  value : @dependency.AnyValue,
) -> Access raise {
  let passed = []
  let end = for next = value {
    if @dependency.object_key.unwrap(next) is Some(object) {
      if object.registry_id() != self.registry_id() {
        raise Unresolved(
          RegistryMismatch,
          "the `\{object.owner_type()}` object belongs to \{object.registry_id()}, and the path to \{self.registry_id()}",
        )
      }
      break Ok(object)
    }
    let id = next.key_id()
    guard self.types.values.get(id) is Some(type_) else {
      break Err(
        (
          CannotStepInto,
          "a path cannot step into a `\{id}` value, because the type is not registered",
        ),
      )
    }
    passed.push((type_, next))
    guard type_.inner is Some(inner) else {
      break Err((UnknownMember, "`\{id}` has no such member"))
    }
    guard inner(next) is Some(next) else {
      break Err((NullValue, "the value before it is null"))
    }
    continue next
  }
  let (name, arguments) : (String?, ArrayView[PathArgument]) = match segment {
    Qualified(found, ..) =>
      match end {
        Ok(object) => return self.resolve_qualified(found, object)
        Err((NullValue, text)) => raise Unresolved(NullValue, text)
        Err(_) =>
          raise Unresolved(
            CannotStepInto,
            "it needs a dependency object, and a `\{value.key_id()}` value has none",
          )
      }
    Property(name) => {
      if end is Ok(object) &&
        @dependency.lookup_property(
          object.owner_type(),
          name,
          registry=self.registry,
        )
        is Some(property) {
        return dependency_access(property, object)
      }
      (Some(name), [])
    }
    Indexer(arguments) => (None, arguments)
  }
  for item in passed {
    let (type_, value) = item
    if type_.members.get(name) is Some(found) {
      return found(value, arguments)
    }
  }
  match end {
    Ok(object) => {
      let owner = object.owner_type()
      guard self.types.find(owner, name) is Some((_, found)) else {
        raise Unresolved(UnknownMember, "`\{owner}` has no such member")
      }
      found(@dependency.object_key.wrap(object), arguments)
    }
    Err((reason, text)) => raise Unresolved(reason, text)
  }
}

///|
/// The member `found` on `object`, which can have any dependency property, but only the registered members of its types.
fn PropertyPath::resolve_qualified(
  self : PropertyPath,
  found : PathMember,
  object : @dependency.DependencyObject,
) -> Access raise {
  match found {
    Dependency(property) => dependency_access(property, object)
    Registered(owner, name) => {
      guard object.owner_type().derives_from(owner) &&
        self.types.find(owner, Some(name)) is Some((_, found)) else {
        raise Unresolved(
          UnknownMember,
          "`\{object.owner_type()}` does not derive from `\{owner}`",
        )
      }
      found(@dependency.object_key.wrap(object), [])
    }
  }
}

///|
/// The failure of the segment at `index` with `error`.
fn PropertyPath::failure(
  self : PropertyPath,
  index : Int32,
  error : Error,
) -> PathFailure {
  let (reason, text) = match error {
    Unresolved(reason, text) => (reason, text)
    _ => (Raised(error), "it cannot be read: \{error}")
  }
  let (start, end) = self.ranges[index]
  let segment = print_segments(
    self.segments[index:index + 1],
    (written, _) => written,
    (written, _) => written,
  )
  { segment: index, start, end, reason, message: "at `\{segment}`: \{text}", }
}

///|
/// What a path gives for a source.
pub(all) enum PathResult {
  Value(@dependency.AnyValue)
  Failure(PathFailure)
}

///|
/// The value, when there is one and it has this key.
pub fn[T] PathResult::read(
  self : PathResult,
  key : @dependency.ValueKey[T],
) -> T? {
  match self {
    Value(value) => key.unwrap(value)
    Failure(_) => None
  }
}

///|
/// Follow the path over the segments `from` to `to`, from the value that `read` gives. `visit` gets each member before it is read.
fn PropertyPath::follow(
  self : PropertyPath,
  from : Int32,
  to : Int32,
  read : () -> @dependency.AnyValue raise,
  visit : (Access) -> Unit raise,
) -> PathResult {
  // An error of `read` is one of the segment before.
  let mut at = from - 1
  try {
    let mut value = read()
    for i in from.. Failure(self.failure(at, error))
  }
}

///|
/// The value at the end of the path from `source`, or the first segment that does not work. This raises no errors.
///
/// Most sources are dependency objects, which `object_key` wraps. A last segment that reads the `None` of an optional type gives this
/// value.
pub fn PropertyPath::get(
  self : PropertyPath,
  source : @dependency.AnyValue,
) -> PathResult {
  self.follow(0, self.segments.length(), () => source, _ => ())
}

///|
/// Why a path did not set a value. Nothing was written then.
pub(all) suberror PathSetError {
  /// The path is the source itself, which no segment sets.
  SourcePath
  /// The path does not reach this segment, or the segment does not take the value.
  CannotSet(PathFailure)
}

///|
/// The description for people.
pub impl Show for PathSetError with fn output(self, logger) {
  match self {
    SourcePath => logger.write_string("the path `.` has no segment to set")
    CannotSet(failure) => logger.write_string(failure.message)
  }
}

///|
pub extend PathSetError with Show::{to_string}

///|
/// Set the last segment of the path from `source` to `value`. This sets the local value of a dependency property, or calls the
/// setter of a registered property or indexer.
///
/// It raises a `PathSetError` when the path does not reach the segment, or when the registered member does not take the value. An
/// error of `set_value` or of the setter is raised as it is.
pub fn PropertyPath::set(
  self : PropertyPath,
  source : @dependency.AnyValue,
  value : @dependency.AnyValue,
) -> Unit raise {
  let last = self.segments.length() - 1
  if last < 0 {
    raise SourcePath
  }
  let receiver = match self.follow(0, last, () => source, _ => ()) {
    Value(receiver) => receiver
    Failure(failure) => raise CannotSet(failure)
  }
  let found = self.resolve(self.segments[last], receiver) catch {
    error => raise CannotSet(self.failure(last, error))
  }
  (found.set)(value) catch {
    Unresolved(_) as error => raise CannotSet(self.failure(last, error))
    error => raise error
  }
}