///|
/// What a type converter converts a value to: text, or a markup extension object, as System.Xaml asks
/// `CanConvertTo(typeof(string))` and `CanConvertTo(typeof(MarkupExtension))`.
#derive(Eq, Hash, Debug)
pub(all) enum ConversionDestination {
  Text
  MarkupExtension
}

///|
/// Converts values of a type from other types, text above all, and back, in the style of
/// System.ComponentModel `TypeConverter` (design D19).
///
/// There is no culture argument: conversions are invariant by contract, as System.Xaml always passes
/// `CultureInfo.InvariantCulture`. `convert_from` and the capability checks accept an absent context,
/// as WPF's `PropertyPath` converts typed indexer arguments without one; a converter that needs a
/// service raises without it. Loading and saving always pass a context.
pub struct TypeConverter {
  priv can_from : (ServiceContext?, @nodes.XamlTypeName) -> Bool
  priv from : (ServiceContext?, @nodes.XamlValue) -> @nodes.XamlValue raise
  priv can_to : (ServiceContext?, ConversionDestination) -> Bool
  priv to : (ServiceContext, @nodes.XamlValue, ConversionDestination) -> @nodes.XamlValue raise
}

///|
/// A converter from the four operations. `can_convert_from` defaults to accepting `x:String` only.
/// Without `convert_to` the converter converts to nothing; with it, `can_convert_to` defaults to
/// text only.
pub fn TypeConverter::new(
  convert_from~ : (ServiceContext?, @nodes.XamlValue) -> @nodes.XamlValue raise,
  can_convert_from? : (ServiceContext?, @nodes.XamlTypeName) -> Bool,
  convert_to? : (ServiceContext, @nodes.XamlValue, ConversionDestination) -> @nodes.XamlValue raise,
  can_convert_to? : (ServiceContext?, ConversionDestination) -> Bool,
) -> TypeConverter {
  let can_from = match can_convert_from {
    Some(check) => check
    None => (_, source) => source == string_type
  }
  let (to, can_to) = match convert_to {
    Some(to) =>
      (
        to,
        match can_convert_to {
          Some(check) => check
          None => (_, destination) => destination is Text
        },
      )
    None =>
      (
        (_, _, destination) => {
          raise ValueError(
            "the converter does not convert to \{destination_text(destination)}",
          )
        },
        can_convert_to.unwrap_or((_, _) => false),
      )
  }
  { can_from, from: convert_from, can_to, to, }
}

///|
/// A converter from text with `parse`, and to text with `format` when it is given.
pub fn TypeConverter::from_text(
  parse : (ServiceContext?, String) -> @nodes.XamlValue raise,
  format? : (ServiceContext, @nodes.XamlValue) -> String raise,
) -> TypeConverter {
  TypeConverter::new(
    convert_from=(context, value) => {
      guard value is String(text) else {
        raise ValueError("the converter converts only from text")
      }
      parse(context, text)
    },
    convert_to?=format.map(format => {
      (context, value, destination) => {
        guard destination is Text else {
          raise ValueError(
            "the converter does not convert to \{destination_text(destination)}",
          )
        }
        String(format(context, value))
      }
    }),
  )
}

///|
fn destination_text(destination : ConversionDestination) -> String {
  match destination {
    Text => "text"
    MarkupExtension => "a markup extension"
  }
}

///|
/// Whether the converter converts values of the type `source`.
pub fn TypeConverter::can_convert_from(
  self : TypeConverter,
  context? : ServiceContext,
  source : @nodes.XamlTypeName,
) -> Bool {
  (self.can_from)(context, source)
}

///|
/// Convert `value` to a value of the converter's type.
pub fn TypeConverter::convert_from(
  self : TypeConverter,
  context? : ServiceContext,
  value : @nodes.XamlValue,
) -> @nodes.XamlValue raise {
  (self.from)(context, value)
}

///|
/// Whether the converter converts values of its type to `destination`.
pub fn TypeConverter::can_convert_to(
  self : TypeConverter,
  context? : ServiceContext,
  destination : ConversionDestination,
) -> Bool {
  (self.can_to)(context, destination)
}

///|
/// Convert `value` to `destination`: a `String` value for text, a markup extension object handle
/// for a markup extension.
pub fn TypeConverter::convert_to(
  self : TypeConverter,
  context : ServiceContext,
  value : @nodes.XamlValue,
  destination : ConversionDestination,
) -> @nodes.XamlValue raise {
  (self.to)(context, value, destination)
}

///|
/// Converts values of a type to text and back when saving, in the style of System.Xaml
/// `ValueSerializer` (design D19). Loading never uses it, as `XamlObjectWriter` never calls
/// `ConvertFromString`.
pub struct ValueSerializer {
  priv can_to_string : (ServiceContext, @nodes.XamlValue) -> Bool
  priv to_string : (ServiceContext, @nodes.XamlValue) -> String raise
  priv can_from_string : (ServiceContext, String) -> Bool
  priv from_string : (ServiceContext, String) -> @nodes.XamlValue raise
}

///|
/// A value serializer. `can_convert_to_string` defaults to true. Without `convert_from_string` it
/// converts no text back; with it, `can_convert_from_string` defaults to true.
pub fn ValueSerializer::new(
  convert_to_string~ : (ServiceContext, @nodes.XamlValue) -> String raise,
  can_convert_to_string? : (ServiceContext, @nodes.XamlValue) -> Bool,
  convert_from_string? : (ServiceContext, String) -> @nodes.XamlValue raise,
  can_convert_from_string? : (ServiceContext, String) -> Bool,
) -> ValueSerializer {
  let (from_string, can_from_string) = match convert_from_string {
    Some(from) => (from, can_convert_from_string.unwrap_or((_, _) => true))
    None =>
      (
        (_, _) => raise ValueError("the value serializer does not read text"),
        can_convert_from_string.unwrap_or((_, _) => false),
      )
  }
  {
    can_to_string: can_convert_to_string.unwrap_or((_, _) => true),
    to_string: convert_to_string,
    can_from_string,
    from_string,
  }
}

///|
pub fn ValueSerializer::can_convert_to_string(
  self : ValueSerializer,
  context : ServiceContext,
  value : @nodes.XamlValue,
) -> Bool {
  (self.can_to_string)(context, value)
}

///|
pub fn ValueSerializer::convert_to_string(
  self : ValueSerializer,
  context : ServiceContext,
  value : @nodes.XamlValue,
) -> String raise {
  (self.to_string)(context, value)
}

///|
pub fn ValueSerializer::can_convert_from_string(
  self : ValueSerializer,
  context : ServiceContext,
  text : String,
) -> Bool {
  (self.can_from_string)(context, text)
}

///|
pub fn ValueSerializer::convert_from_string(
  self : ValueSerializer,
  context : ServiceContext,
  text : String,
) -> @nodes.XamlValue raise {
  (self.from_string)(context, text)
}

///|
/// A function that a type registers to read its values from text, as Avalonia converts with a static
/// `Parse(string)` method (design D19). For text it comes before the type converter.
pub type ParseFunction = (String) -> @nodes.XamlValue raise

///|
/// What a failed conversion was for.
#derive(Eq, Debug)
pub(all) enum ConversionSubject {
  /// A member value.
  OfMember(@nodes.XamlMemberName)
  /// A value of a type, such as element text.
  OfType(@nodes.XamlTypeName)
}

///|
/// A conversion failed. It names the member or type, the input and the converter's message, as
/// System.Xaml `TypeConverterFailed` does.
#derive(Eq, Debug)
pub(all) suberror ConversionError {
  ConversionFailed(
    subject~ : ConversionSubject,
    input~ : String,
    message~ : String,
  )
}

///|
pub fn ConversionError::message(self : ConversionError) -> String {
  let ConversionFailed(subject~, input~, message~) = self
  let target = match subject {
    OfMember(name) => "the member \{member_text(name)}"
    OfType(name) => "the type \{name}"
  }
  "cannot convert \{input} for \{target}: \{message}"
}

///|
fn member_text(name : @nodes.XamlMemberName) -> String {
  match name {
    Member(owner~, name~) => "\{name} of \{owner}"
    Attached(owner~, name~) => "\{owner}.\{name}"
    Directive(namespace_uri~, name~)
    | UnknownDirective(namespace_uri~, name~) => "{\{namespace_uri}}\{name}"
  }
}

///|
/// The message of an error that a registered function raised.
pub fn error_message(error : Error) -> String {
  try {
    raise error
  } catch {
    ValueError(message) => message
    Failure(message) => message
    ConversionFailed(subject~, input~, message~) =>
      ConversionError::ConversionFailed(subject~, input~, message~).message()
    UnknownType(name) => TypeResolutionError::UnknownType(name).message()
    ArityMismatch(name~, expected~, given~) =>
      TypeResolutionError::ArityMismatch(name~, expected~, given~).message()
    MalformedClrNamespace(namespace_uri~) =>
      NamespaceError::MalformedClrNamespace(namespace_uri~).message()
    AmbiguousType(name~, namespace_uri~, scopes~) =>
      NamespaceError::AmbiguousType(name~, namespace_uri~, scopes~).message()
    Conflicts(list) => SchemaError::Conflicts(list).message()
    e => e.to_string()
  }
}

///|
/// How an input shows in a conversion error: text quoted, other values in constructor syntax.
fn input_text(value : @nodes.XamlValue) -> String {
  match value {
    String(text) => @debug.to_string(text)
    other => @debug.to_string(other)
  }
}

///|
/// The XAML type of a value as a converter's source type: the primitive type of a primitive, the
/// type of an object handle, and `None` for null and lists.
pub fn value_type_name(value : @nodes.XamlValue) -> @nodes.XamlTypeName? {
  match value {
    Null | List(_) => None
    Bool(_) => Some(boolean_type)
    Byte(_) => Some(byte_type)
    Int16(_) => Some(int16_type)
    Int(_) => Some(int32_type)
    Int64(_) => Some(int64_type)
    Single(_) => Some(single_type)
    Double(_) => Some(double_type)
    Char(_) => Some(char_type)
    String(_) => Some(string_type)
    Object(handle) => Some(handle.type_name)
  }
}

///|
/// Convert `value` with `converter`, raising `ConversionError` for `subject` when the converter does
/// not accept the source type or fails.
fn convert_with(
  converter : TypeConverter,
  subject : ConversionSubject,
  value : @nodes.XamlValue,
  context : ServiceContext?,
) -> @nodes.XamlValue raise ConversionError {
  guard converter_accepts(converter, value, context) else {
    let from = value_type_name(value)
      .map(s => s.to_string())
      .unwrap_or("this value")
    raise ConversionFailed(
      subject~,
      input=input_text(value),
      message="the converter does not convert from \{from}",
    )
  }
  converter.convert_from(context?, value) catch {
    e =>
      raise ConversionFailed(
        subject~,
        input=input_text(value),
        message=error_message(e),
      )
  }
}

///|
fn converter_accepts(
  converter : TypeConverter,
  value : @nodes.XamlValue,
  context : ServiceContext?,
) -> Bool {
  value_type_name(value) is Some(source) &&
  converter.can_convert_from(context?, source)
}

///|
/// Whether `convert_from` accepts values of the type of `value`. Loading passes a value that it does not
/// accept through unconverted, as System.Xaml `ClrObjectRuntime.CreateObjectWithTypeConverter`.
pub fn XamlType::can_convert_from(
  self : XamlType,
  value : @nodes.XamlValue,
  context? : ServiceContext,
) -> Bool {
  (value is String(_) && self.parse_function is Some(_)) ||
  (
    self.type_converter is Some(converter) &&
    converter_accepts(converter, value, context)
  )
}

///|
/// Convert `value` to a value of this type: text with the parse function when one is registered,
/// else with the type converter (design D19). It raises `ConversionError` naming the type.
pub fn XamlType::convert_from(
  self : XamlType,
  value : @nodes.XamlValue,
  context? : ServiceContext,
) -> @nodes.XamlValue raise ConversionError {
  let subject = OfType(self.name)
  match (value, self.parse_function) {
    (String(text), Some(parse)) =>
      parse(text) catch {
        e =>
          raise ConversionFailed(
            subject~,
            input=input_text(value),
            message=error_message(e),
          )
      }
    _ =>
      match self.type_converter {
        Some(converter) => convert_with(converter, subject, value, context)
        None =>
          raise ConversionFailed(
            subject~,
            input=input_text(value),
            message="the type has no type converter",
          )
      }
  }
}

///|
/// The type converter of `member`: its own, attached members included, else the converter of its
/// value type, as System.Xaml `XamlMember.LookupTypeConverter` finds it.
pub fn SchemaContext::member_type_converter(
  self : SchemaContext,
  target : XamlMember,
) -> TypeConverter? {
  match target.type_converter {
    Some(converter) => Some(converter)
    None =>
      target.value_type.bind(t => self.get_type(t)).bind(t => t.type_converter)
  }
}

///|
/// Whether text content goes to the content member `target`: its converter is the built-in
/// `x:String` or `x:Object` one, or its value type is a collection of `x:String` or `x:Object`
/// items, as System.Xaml `XamlPullParser.CanAcceptString` decides (design D17).
pub fn SchemaContext::member_accepts_string(
  self : SchemaContext,
  target : XamlMember,
) -> Bool {
  if self.member_type_converter(target) is Some(converter) &&
    (
      physical_equal(converter, string_converter) ||
      physical_equal(converter, object_converter)
    ) {
    return true
  }
  guard target.value_type.bind(t => self.get_type(t)) is Some(t) &&
    t.is_collection() else {
    return false
  }
  t.item_type == Some(string_type) || t.item_type == Some(object_type)
}

///|
/// The value serializer of `member`: its own, else its value type's (the type's own, its base
/// types' nearest first, then the built-in one of the exact type), as System.Xaml
/// `LookupValueSerializer` finds it. A nullable member uses its underlying type's.
pub fn SchemaContext::member_value_serializer(
  self : SchemaContext,
  target : XamlMember,
) -> ValueSerializer? {
  match target.value_serializer {
    Some(serializer) => Some(serializer)
    None =>
      target.value_type
      .bind(t => self.get_type(t))
      .bind(t => t.value_serializer)
  }
}

///|
/// Whether `convert_member_value` accepts values of the type of `value` for `target`.
pub fn SchemaContext::can_convert_member_value(
  self : SchemaContext,
  target : XamlMember,
  value : @nodes.XamlValue,
  context? : ServiceContext,
) -> Bool {
  match target.type_converter {
    Some(converter) => converter_accepts(converter, value, context)
    None =>
      target.value_type.bind(t => self.get_type(t)) is Some(value_type) &&
      value_type.can_convert_from(value, context?)
  }
}

///|
/// Convert `value` for `member`: with the member's converter when it has one; otherwise as its
/// value type converts it, text with the type's parse function first (design D19). It raises
/// `ConversionError` naming the member.
pub fn SchemaContext::convert_member_value(
  self : SchemaContext,
  target : XamlMember,
  value : @nodes.XamlValue,
  context? : ServiceContext,
) -> @nodes.XamlValue raise ConversionError {
  let subject = OfMember(target.member_name())
  if target.type_converter is Some(converter) {
    return convert_with(converter, subject, value, context)
  }
  guard target.value_type.bind(t => self.get_type(t)) is Some(value_type) else {
    raise ConversionFailed(
      subject~,
      input=input_text(value),
      message="the member has no type converter",
    )
  }
  value_type.convert_from(value, context?) catch {
    ConversionFailed(input~, message~, ..) =>
      raise ConversionFailed(subject~, input~, message~)
  }
}