// What paths find on values, besides dependency properties.

///|
/// What this package keeps in a registry. Nothing in it holds the registry.
priv struct TypeTable {
  values : Map[@dependency.ValueKeyId, ValueType]
  objects : Map[@dependency.OwnerType, Members]
}

///|
/// The members of a type by name. The indexer has no name.
type Members = Map[String?, Member]

///|
/// Gives the access to a member of a value of its type. An indexer gets its arguments.
type Member = (@dependency.AnyValue, ArrayView[PathArgument]) -> Access raise

///|
priv struct ValueType {
  members : Members
  /// Gives the value inside, or `None` when that is null.
  mut inner : ((@dependency.AnyValue) -> @dependency.AnyValue?)?
}

///|
let type_table_key : @dependency.ValueKey[TypeTable] = @dependency.ValueKey::by_identity(
  "TypeTable",
)

///|
/// The table of `registry`, which gets one when it has none.
fn type_table(registry : @dependency.PropertyRegistry) -> TypeTable {
  if registry.extension(type_table_key) is Some(table) {
    return table
  }
  let table = { values: Map([]), objects: Map([]), }
  registry.set_extension(type_table_key, table)
  table
}

///|
/// The member of `owner`, or else of the nearest type that it derives from, and the type that has it.
fn TypeTable::find(
  self : TypeTable,
  owner : @dependency.OwnerType,
  name : String?,
) -> (@dependency.OwnerType, Member)? {
  for next = Some(owner); next is Some(owner); next = owner.base_type() {
    if self.objects.get(owner) is Some(members) &&
      members.get(name) is Some(found) {
      return Some((owner, found))
    }
  }
  None
}

///|
/// A type whose values have members for paths. .NET finds these by reflection, which MoonBit does not have.
pub struct PathType[T] {
  priv name : String
  priv key : @dependency.ValueKey[T]
  priv members : Members
}

///|
/// Let paths step into the values of `key`. `add_property` and `add_indexer` add the members.
///
/// `inner` gives a value inside this one, whose members paths find too, such as the dependency object of a control. `None` means
/// that the value is null. See `register_optional` for an optional type.
///
/// A type can be registered again, to add more members, but it has at most one `inner`.
pub fn[T] register_value_type(
  key : @dependency.ValueKey[T],
  inner? : (T) -> @dependency.AnyValue?,
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> PathType[T] raise @dependency.DependencyError {
  let id = key.id()
  if id == @dependency.object_key.id() {
    raise InvalidRegistration(
      "the members of dependency objects are registered for their owner types, with `register_object_type`",
    )
  }
  let found = type_table(registry).values.get_or_init(id, () => {
    members: Map([]),
    inner: None,
  })
  if inner is Some(inner) {
    if found.inner is Some(_) {
      raise InvalidRegistration(
        "the inner value of `\{id}` is registered already",
      )
    }
    found.inner = Some(value => inner(value_of(key, value)))
  }
  { name: id.to_string(), key, members: found.members, }
}

///|
/// Let paths step into the values of an optional type. `None` is a null value, and the others have the members that `key` has.
pub fn[T] register_optional(
  optional : @dependency.ValueKey[T?],
  key : @dependency.ValueKey[T],
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> Unit raise @dependency.DependencyError {
  ignore(
    register_value_type(
      optional,
      inner=value => value.map(value => key.wrap(value)),
      registry~,
    ),
  )
}

///|
/// Let paths find members that are no dependency properties on the objects of the type `owner`, and of the types that derive from
/// it. `add_property` and `add_indexer` add them. Their functions get the dependency object, whose `host` is the control.
///
/// A type can be registered again, to add more members.
pub fn register_object_type(
  owner : @dependency.OwnerType,
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> PathType[@dependency.DependencyObject] raise @dependency.DependencyError {
  registry.check_owner(owner)
  let members = type_table(registry).objects.get_or_init(owner, () => Map([]))
  { name: owner.name(), key: @dependency.object_key, members, }
}

///|
/// Add a property with values of `key`.
///
/// - `get` reads it. When it raises an error, the path has no value.
/// - `set` writes it. Without it, the property is read-only.
/// - `subscribe` calls the given function after each change of the property, and returns a function that ends this. Without it, an
///   observer does not hear of the changes.
pub fn[T, V] PathType::add_property(
  self : PathType[T],
  name : String,
  key : @dependency.ValueKey[V],
  get~ : (T) -> V raise,
  set? : (T, V) -> Unit raise,
  subscribe? : (T, () -> Unit raise) -> () -> Unit,
) -> Unit raise @dependency.DependencyError {
  if name.is_empty() {
    raise InvalidRegistration("a property of `\{self.name}` needs a name")
  }
  self.add(Some(name), (value, _) => {
    access(
      key,
      () => get(value),
      set.map(set => next => set(value, next)),
      subscribe.map(subscribe => changed => subscribe(value, changed)),
    )
  })
}

///|
/// Add the indexer, with items of `key`. A type can have one.
///
/// `parameters` says which arguments it takes, such as `int_parameter`. The rest is as for `add_property`. `get` and `set` also get
/// the arguments, and `subscribe` is for a change of any item.
pub fn[T, P, V] PathType::add_indexer(
  self : PathType[T],
  parameters : Parameters[P],
  key : @dependency.ValueKey[V],
  get~ : (T, P) -> V raise,
  set? : (T, P, V) -> Unit raise,
  subscribe? : (T, () -> Unit raise) -> () -> Unit,
) -> Unit raise @dependency.DependencyError {
  self.add(None, (value, arguments) => {
    let arguments = parameters.read(arguments)
    access(
      key,
      () => get(value, arguments),
      set.map(set => next => set(value, arguments, next)),
      subscribe.map(subscribe => changed => subscribe(value, changed)),
    )
  })
}

///|
fn[T] PathType::add(
  self : PathType[T],
  name : String?,
  added : (T, ArrayView[PathArgument]) -> Access raise,
) -> Unit raise @dependency.DependencyError {
  if self.members.contains(name) {
    let what = match name {
      Some(name) => "`\{self.name}.\{name}`"
      None => "the indexer of `\{self.name}`"
    }
    raise InvalidRegistration("\{what} is registered for paths already")
  }
  let key = self.key
  self.members[name] = (value, arguments) => {
    added(value_of(key, value), arguments)
  }
}

///|
/// The value in `any`, which `key` has wrapped.
fn[T] value_of(key : @dependency.ValueKey[T], any : @dependency.AnyValue) -> T {
  guard key.unwrap(any) is Some(value) else {
    abort("a `\{any.key_id()}` value is read with the key `\{key.id()}`")
  }
  value
}

///|
/// The parameters of an indexer, whose arguments together are a `P`.
pub struct Parameters[P] {
  priv count : Int32
  /// Takes `count` arguments.
  priv take : (ArrayView[PathArgument]) -> P raise
}

///|
/// One parameter with values of `key`. `parse` makes the value of an argument that is text. An argument with a type has to have a
/// value of `key`.
pub fn[P] Parameters::new(
  key : @dependency.ValueKey[P],
  parse : (String) -> P raise,
) -> Parameters[P] {
  {
    count: 1,
    take: arguments => {
      match arguments[0] {
        Text(text) =>
          parse(text) catch {
            error =>
              raise Unresolved(
                InvalidArgument,
                "the argument \{@debug.to_string(text)} is no `\{key.id()}` value: \{error}",
              )
          }
        Typed(written~, text~, value~, ..) => {
          guard key.unwrap(value) is Some(value) else {
            raise Unresolved(
              InvalidArgument,
              "the argument `(\{written})\{text}` is a `\{value.key_id()}` value, and the indexer takes a `\{key.id()}` value",
            )
          }
          value
        }
      }
    },
  }
}

///|
/// These parameters and then those of `other`.
pub fn[P, Q] Parameters::then(
  self : Parameters[P],
  other : Parameters[Q],
) -> Parameters[(P, Q)] {
  let count = self.count
  {
    count: count + other.count,
    take: arguments => {
      ((self.take)(arguments[:count]), (other.take)(arguments[count:]))
    },
  }
}

///|
fn[P] Parameters::read(
  self : Parameters[P],
  arguments : ArrayView[PathArgument],
) -> P raise {
  if arguments.length() != self.count {
    raise Unresolved(
      InvalidArgument,
      "the number of arguments is \{arguments.length()}, and the indexer takes \{self.count}",
    )
  }
  (self.take)(arguments)
}

///|
/// A parameter for a number, such as the position in a list. It reads text as .NET reads an `Int32`.
pub let int_parameter : Parameters[Int32] = Parameters::new(
  @dependency.int_key,
  text => {
    guard parse_int(text) is Some(value) else { raise NotAnInt }
    value
  },
)

///|
priv suberror NotAnInt

///|
impl Show for NotAnInt with fn output(_, logger) {
  logger.write_string("it is not a whole number of 32 bits")
}

///|
/// A parameter for text, such as the key in a map.
pub let string_parameter : Parameters[String] = Parameters::new(
  @dependency.string_key,
  text => text,
)