// Conversions between the values of XAML and those of dependency properties.

///|
/// How a `XamlValue` becomes a value of a dependency property of type `T`, and back.
///
/// There is one for each shared value key of `moonrockz/dependency-object` that has a XAML type: `int_conversion` for
/// `int_key`, `double_conversion` for `double_key`, and so on.
pub struct PropertyConversion[T] {
  /// The XAML type of the values, to which text converts first.
  value_type : @nodes.XamlTypeName
  /// Whether null is a value too.
  nullable : Bool
  priv from_xaml : (DependencyTypes, @nodes.XamlValue) -> T raise
  priv to_xaml : (DependencyTypes, T) -> @nodes.XamlValue raise
}

///|
/// A conversion with values of the XAML type `value_type`. The functions raise an error for a value that they do not take.
pub fn[T] PropertyConversion::new(
  value_type : @nodes.XamlTypeName,
  from_xaml : (@nodes.XamlValue) -> T raise,
  to_xaml : (T) -> @nodes.XamlValue raise,
) -> PropertyConversion[T] {
  {
    value_type,
    nullable: false,
    from_xaml: (_, value) => from_xaml(value),
    to_xaml: (_, value) => to_xaml(value),
  }
}

///|
/// The conversion for properties that can also be `None`, which is null in XAML.
pub fn[T] PropertyConversion::optional(
  self : PropertyConversion[T],
) -> PropertyConversion[T?] {
  {
    value_type: self.value_type,
    nullable: true,
    from_xaml: (types, value) => {
      if value is Null {
        None
      } else {
        Some((self.from_xaml)(types, value))
      }
    },
    to_xaml: (types, value) => {
      match value {
        Some(value) => (self.to_xaml)(types, value)
        None => Null
      }
    },
  }
}

///|
/// The conversion of the values that `key` wraps as objects of the XAML type `value_type`. It does not keep the type of an
/// object of a derived type, so use `PropertyConversion::value` for a property that takes those.
pub fn[T] PropertyConversion::object(
  value_type : @nodes.XamlTypeName,
  key : @nodes.ObjectKey[T],
) -> PropertyConversion[T] {
  simple_conversion(
    value_type,
    value => if value is Object(handle) { key.unwrap(handle) } else { None },
    value => Object(key.wrap(value_type, value)),
  )
}

///|
/// The conversion for properties that keep the `XamlValue`s of the XAML type `value_type`, with the key `xaml_value_key`.
pub fn PropertyConversion::value(
  value_type : @nodes.XamlTypeName,
) -> PropertyConversion[@nodes.XamlValue] {
  PropertyConversion::new(value_type, value => value, value => value)
}

///|
/// A conversion with a function that gives `None` for a value that it does not take.
fn[T] simple_conversion(
  value_type : @nodes.XamlTypeName,
  read : (@nodes.XamlValue) -> T?,
  write : (T) -> @nodes.XamlValue,
) -> PropertyConversion[T] {
  PropertyConversion::new(
    value_type,
    value => {
      guard read(value) is Some(found) else {
        raise not_taken(value_type, value)
      }
      found
    },
    value => write(value),
  )
}

///|
fn not_taken(
  name : @nodes.XamlTypeName,
  value : @nodes.XamlValue,
) -> ValueError {
  ValueError("\{name} does not take \{input_text(value)}")
}

///|
/// `x:Boolean` for `bool_key`.
pub let bool_conversion : PropertyConversion[Bool] = simple_conversion(
  boolean_type,
  value => if value is Bool(b) { Some(b) } else { None },
  b => Bool(b),
)

///|
/// `x:Byte` for `byte_key`.
pub let byte_conversion : PropertyConversion[Byte] = simple_conversion(
  byte_type,
  value => if value is Byte(b) { Some(b) } else { None },
  b => Byte(b),
)

///|
/// `x:Int16` for `int16_key`.
pub let int16_conversion : PropertyConversion[Int16] = simple_conversion(
  int16_type,
  value => if value is Int16(n) { Some(n) } else { None },
  n => Int16(n),
)

///|
/// `x:Int32` for `int_key`.
pub let int_conversion : PropertyConversion[Int32] = simple_conversion(
  int32_type,
  value => if value is Int(n) { Some(n) } else { None },
  n => Int(n),
)

///|
/// `x:Int64` for `int64_key`.
pub let int64_conversion : PropertyConversion[Int64] = simple_conversion(
  int64_type,
  value => if value is Int64(n) { Some(n) } else { None },
  n => Int64(n),
)

///|
/// `x:Single` for `float_key`.
pub let float_conversion : PropertyConversion[Float] = simple_conversion(
  single_type,
  value => if value is Single(f) { Some(f) } else { None },
  f => Single(f),
)

///|
/// `x:Double` for `double_key`.
pub let double_conversion : PropertyConversion[Double] = simple_conversion(
  double_type,
  value => if value is Double(d) { Some(d) } else { None },
  d => Double(d),
)

///|
/// `x:Char` for `char_key`. An `x:Char` is one UTF-16 code unit, and a `Char` is a whole character. So half of a surrogate pair
/// is no `Char`, and a character above U+FFFF is no `x:Char`.
pub let char_conversion : PropertyConversion[Char] = PropertyConversion::new(
  char_type,
  value => {
    guard value is Char(unit) && unit.to_int().to_char() is Some(c) else {
      raise not_taken(char_type, value)
    }
    c
  },
  c => {
    if c.to_int() > 0xFFFF {
      raise not_taken(char_type, String(c.to_string()))
    }
    Char(c.to_int().to_uint16())
  },
)

///|
/// `x:String` for `string_key`.
pub let string_conversion : PropertyConversion[String] = simple_conversion(
  string_type,
  value => if value is String(s) { Some(s) } else { None },
  s => String(s),
)

///|
/// `x:Decimal` for `decimal_value_key`.
pub let decimal_conversion : PropertyConversion[XamlDecimal] = simple_conversion(
  decimal_type, as_decimal, decimal_value,
)

///|
/// `x:TimeSpan` for `time_span_value_key`.
pub let time_span_conversion : PropertyConversion[XamlTimeSpan] = simple_conversion(
  time_span_type, as_time_span, time_span_value,
)

///|
/// `x:Uri` for `uri_value_key`.
pub let uri_conversion : PropertyConversion[XamlUri] = simple_conversion(
  uri_type, as_uri, uri_value,
)

///|
/// The key for the values of dependency properties that keep `XamlValue`s.
pub let xaml_value_key : @dependency.ValueKey[@nodes.XamlValue] = @dependency.ValueKey::new(
  "XamlValue",
  show=input_text,
)

///|
pub let decimal_value_key : @dependency.ValueKey[XamlDecimal] = @dependency.ValueKey::new(
  "XamlDecimal",
)

///|
pub let time_span_value_key : @dependency.ValueKey[XamlTimeSpan] = @dependency.ValueKey::new(
  "XamlTimeSpan",
)

///|
pub let uri_value_key : @dependency.ValueKey[XamlUri] = @dependency.ValueKey::new(
  "XamlUri",
)

///|
/// The key with which `x:Object` converts an object that has no other conversion to an `AnyValue`.
pub let xaml_object_key : @dependency.ValueKey[@nodes.XamlObject] = @dependency.ValueKey::new(
  "XamlObject",
)

///|
/// The key with which `x:Object` converts null to an `AnyValue`.
pub let null_value_key : @dependency.ValueKey[Unit] = @dependency.ValueKey::new(
  "null",
)