// Property paths as values, such as `Target="Child.(Grid.Row)"`.

///|
/// The key of the values of all types that `property_path_type` gives. Two values are equal when their paths are.
pub let property_path_key : @nodes.ObjectKey[@path.PropertyPath] = @nodes.ObjectKey::new(equal=(
    a,
    b,
  ) => a == b,
)

///|
/// A XAML type `name` of `namespace_uri` whose values are property paths of `registry`, as WPF's `PropertyPath`.
///
/// Types in a path have the prefixes of the document. In `(local:Grid.Row)` it is a linked type, which has a `dependency_owner`. In
/// `[(x:Int32)1]` it is one whose values convert from text and have an `any_value_converter`, and it converts the text without a
/// context. A saved path names the type that stands for the owner type of the member, and its prefixes are those of the new
/// document.
pub fn property_path_type(
  namespace_uri : String,
  name : String,
  registry~ : @dependency.PropertyRegistry = @dependency.PropertyRegistry::default(),
) -> XamlTypeDefinition {
  let converter = type_name => path_converter(type_name, registry)
  let definition = XamlTypeDefinition::new(namespace_uri, name)
  { ..definition, type_converter: Some(converter), }.object_key(
    property_path_key,
  )
}

///|
/// The converter of the paths of `registry`, whose values have the type `type_name`.
fn path_converter(
  type_name : @nodes.XamlTypeName,
  registry : @dependency.PropertyRegistry,
) -> TypeConverter {
  let registry_id = registry.id()
  TypeConverter::from_text(
    (context, text) => {
      let path = @path.parse(text, resolver=path_resolver(context), registry~)
      Object(property_path_key.wrap(type_name, path))
    },
    format=(context, value) => {
      guard value is Object(handle) &&
        property_path_key.unwrap(handle) is Some(path) else {
        raise ValueError("the value is no property path")
      }
      if path.registry_id() != registry_id {
        raise ValueError(
          "the path `\{path}` belongs to \{path.registry_id()}, and \{type_name} to \{registry_id}",
        )
      }
      path.print_with(path_namer(context))
    },
  )
}

///|
/// Finds the types of a path by the names that they have in a document.
fn path_resolver(context : ServiceContext?) -> @path.PathResolver {
  @path.PathResolver::new(
    owner=(prefix, name) => {
      guard type_in_path(context, prefix, name).dependency_owner()
        is Some(owner) else {
        raise UnknownType
      }
      owner
    },
    argument_type=(prefix, name) => {
      let found = type_in_path(context, prefix, name)
      Some(
        @path.ArgumentType::new(found.name.to_string(), text => {
          argument_value(found, text) catch {
            error => raise ArgumentError(error_message(error))
          }
        }),
      )
    },
  )
}

///|
fn type_in_path(
  context : ServiceContext?,
  prefix : String?,
  name : String,
) -> XamlType raise @path.PathResolveError {
  guard context
    is Some(
      {
        resolve_type: Some(resolve_type),
        resolve_prefix: Some(resolve_prefix),
        schema_context,
        ..
      },
    ) else {
    raise UnknownType
  }
  let text = match prefix {
    Some(prefix) => {
      // `resolve_type` ignores this white space too.
      if resolve_prefix(prefix.trim().to_owned()) is None {
        raise UnknownPrefix
      }
      "\{prefix}:\{name}"
    }
    None => name
  }
  guard resolve_type(text) is Some(found) &&
    schema_context.get_type(found) is Some(found) else {
    raise UnknownType
  }
  found
}

///|
/// The value of an argument of the type `type_`. As in WPF, the conversion gets no context.
fn argument_value(
  type_ : XamlType,
  text : String,
) -> @dependency.AnyValue raise {
  let value = type_.convert_from(String(text))
  guard type_.any_value_converter() is Some(convert) else {
    raise ValueError("\{type_.name} has no `any_value_converter`")
  }
  convert(value)
}

///|
/// An error whose text is its message, which the error of the path shows.
priv suberror ArgumentError {
  ArgumentError(String)
}

///|
impl Show for ArgumentError with fn output(self, logger) {
  let ArgumentError(message) = self
  logger.write_string(message)
}

///|
/// Names the types of a path for the document that is saved.
fn path_namer(context : ServiceContext) -> @path.PathNamer {
  let { schema_context, lookup_prefix, .. } = context
  let write = (name : @nodes.XamlTypeName) => {
    guard lookup_prefix is Some(lookup_prefix) else {
      raise ValueError(
        "writing the type name \{name} needs a context that looks up prefixes",
      )
    }
    name.to_text(namespace_uri => Some(lookup_prefix(namespace_uri)))
  }
  @path.PathNamer::new(
    owner=owner => {
      guard schema_context.xaml_type_for_owner(owner) is Some(found) else {
        raise ValueError("no XAML type stands for the owner type `\{owner}`")
      }
      write(found.name)
    },
    argument_type=text => {
      // This is the text that `path_resolver` made.
      guard text is ['{', .. rest] &&
        rest.rev_find("}") is Some(end) &&
        schema_context.get_type(
          @nodes.XamlTypeName::new(
            rest[:end].to_owned(),
            rest[end + 1:].to_owned(),
          ),
        )
        is Some(found) else {
        raise ValueError("the type `\{text}` of an argument is no XAML type")
      }
      write(found.name)
    },
  )
}