///|
/// Watches what a path gives for a source, until `dispose`.
pub struct PathObserver {
  /// The path and the callback, until `dispose`.
  priv mut target : (PropertyPath, (PathResult) -> Unit raise)?
  /// The members that the path has reached, in the order of the segments.
  priv watched : Array[Watched]
  /// The number of refreshes, with which one sees that another one has overtaken it.
  priv mut refreshes : Int32
  /// What the nesting limit calls the observer.
  priv label : String
}

///|
/// A member on the path with its subscription. Both are `None` when the observer does not watch it any more.
priv struct Watched {
  mut access : Access?
  mut unsubscribe : (() -> Unit)?
}

///|
/// Call `callback` with what the path gives for `source` now, and again after each change on the path. The observer hears of the
/// changes of dependency properties, and of registered members that have `subscribe`.
///
/// After a change, the observer reads the changed member again, follows the path from there, and calls `callback` with the result,
/// also when it is equal to the last one. An error of `callback` reaches the code that made the change, and the observer goes on.
/// An error of the first call is raised here, and nothing is observed.
///
/// The observer and the objects on the path hold each other. Call `dispose` before you drop them, because native and wasm do not
/// free such a circle.
pub fn PropertyPath::observe(
  self : PropertyPath,
  source : @dependency.AnyValue,
  callback : (PathResult) -> Unit raise,
) -> PathObserver raise {
  let observer = {
    target: Some((self, callback)),
    watched: [],
    refreshes: 0,
    label: "the observer of `\{self}`",
  }
  errdefer observer.dispose()
  observer.refresh(0, () => source)
  observer
}

///|
/// Keep the first `kept` members, follow the path from there with the value that `read` gives, and call the callback.
///
/// Getters, subscriptions and the callback can change the path. Such a change refreshes the path from a member that is watched now to
/// its end, so that the refresh in which it happens has nothing left to do, and calls no more getters. The same is so after `dispose`.
fn PathObserver::refresh(
  self : PathObserver,
  kept : Int32,
  read : () -> @dependency.AnyValue raise,
) -> Unit raise {
  guard self.target is Some((path, callback)) else { return }
  @dependency.guard_nesting(self.label, () => {
    self.refreshes += 1
    let number = self.refreshes
    self.release(kept)
    if self.refreshes != number {
      return
    }
    let check = () => if self.refreshes != number { raise Overtaken }
    let result = path.follow(kept, path.segments.length(), read, found => {
      check()
      self.watch(found)
      check()
    })
    if self.refreshes == number {
      callback(result)
    }
  })
}

///|
/// Ends a refresh after `dispose`, or when another one has overtaken it.
priv suberror Overtaken

///|
/// Watch the next member of the path.
fn PathObserver::watch(self : PathObserver, found : Access) -> Unit {
  let added = { access: Some(found), unsubscribe: None, }
  self.watched.push(added)
  let count = self.watched.length()
  let unsubscribe = (found.subscribe)(() => {
    // Change handlers run over a copy of their list, so this can still run after the subscription has ended.
    if added.access is Some(access) {
      self.refresh(count, access.get)
    }
  })
  if added.access is Some(_) {
    added.unsubscribe = Some(unsubscribe)
  } else {
    unsubscribe()
  }
}

///|
/// Watch only the first `kept` members.
fn PathObserver::release(self : PathObserver, kept : Int32) -> Unit {
  let ended = []
  while self.watched.length() > kept && self.watched.pop() is Some(item) {
    item.access = None
    if item.unsubscribe is Some(unsubscribe) {
      item.unsubscribe = None
      ended.push(unsubscribe)
    }
  }
  // This is code of the user, which can start another refresh.
  for unsubscribe in ended {
    unsubscribe()
  }
}

///|
/// Stop watching. The callback is not called any more, also not for a change that is being notified now.
pub fn PathObserver::dispose(self : PathObserver) -> Unit {
  self.refreshes += 1
  self.target = None
  self.release(0)
}