///|
/// `x:Byte`, whose values are `Byte`.
pub let byte_type : @nodes.XamlTypeName = xaml_type("Byte")

///|
/// `x:Int16`, whose values are `Int16`.
pub let int16_type : @nodes.XamlTypeName = xaml_type("Int16")

///|
/// `x:Single`, whose values are `Single` (MoonBit `Float`).
pub let single_type : @nodes.XamlTypeName = xaml_type("Single")

///|
/// `x:Char`, whose values are `Char`: one UTF-16 code unit.
pub let char_type : @nodes.XamlTypeName = xaml_type("Char")

///|
/// `x:Decimal`, whose values are handles that `decimal_value` makes.
pub let decimal_type : @nodes.XamlTypeName = xaml_type("Decimal")

///|
/// `x:TimeSpan`, whose values are handles that `time_span_value` makes.
pub let time_span_type : @nodes.XamlTypeName = xaml_type("TimeSpan")

///|
/// `x:Uri`, whose values are handles that `uri_value` makes.
pub let uri_type : @nodes.XamlTypeName = xaml_type("Uri")

///|
/// The value of `x:Decimal`: a coefficient whose absolute value is below 2^96 and a scale from 0 to
/// 28, as `System.Decimal` holds (design D12, 2F66). The value is `coefficient / 10^scale`. Two
/// decimals are equal by numeric value, so `1.5` equals `1.50`, and the scale is kept for text.
pub struct XamlDecimal {
  priv coefficient : @bigint.BigInt
  priv scale : Int32
}

///|
/// 2^96, the bound of a decimal's coefficient.
let decimal_limit : @bigint.BigInt = @bigint.BigInt::from_int(1) << 96

///|
/// A decimal, or `ValueError` naming `x:Decimal` when the coefficient or scale is out of range.
pub fn XamlDecimal::new(
  coefficient : @bigint.BigInt,
  scale : Int32,
) -> XamlDecimal raise ValueError {
  if scale < 0 || scale > 28 {
    raise ValueError("x:Decimal scale \{scale} is not between 0 and 28")
  }
  let magnitude = if coefficient < @bigint.BigInt::from_int(0) {
    -coefficient
  } else {
    coefficient
  }
  if magnitude >= decimal_limit {
    raise ValueError(
      "x:Decimal coefficient \{coefficient} is not below 2^96 in absolute value",
    )
  }
  { coefficient, scale, }
}

///|
pub fn XamlDecimal::coefficient(self : XamlDecimal) -> @bigint.BigInt {
  self.coefficient
}

///|
pub fn XamlDecimal::scale(self : XamlDecimal) -> Int32 {
  self.scale
}

///|
/// The coefficient and scale without trailing zeros, the same for every equal decimal.
fn XamlDecimal::normalized(self : XamlDecimal) -> (@bigint.BigInt, Int32) {
  let ten = @bigint.BigInt::from_int(10)
  let zero = @bigint.BigInt::from_int(0)
  let mut coefficient = self.coefficient
  let mut scale = self.scale
  if coefficient == zero {
    return (zero, 0)
  }
  while scale > 0 && coefficient % ten == zero {
    coefficient = coefficient / ten
    scale -= 1
  }
  (coefficient, scale)
}

///|
pub impl Eq for XamlDecimal with fn equal(self, other) {
  self.normalized() == other.normalized()
}

///|
pub impl Hash for XamlDecimal with fn hash_combine(self, hasher) {
  let (coefficient, scale) = self.normalized()
  hasher.combine_string(coefficient.to_string())
  hasher.combine_int(scale)
}

///|
pub impl Debug for XamlDecimal with fn to_repr(self) {
  @debug.Repr::literal("XamlDecimal(\{self})")
}

///|
/// Invariant text with `scale` digits after the point, as `Decimal.ToString` writes it: `1.50`.
pub impl Show for XamlDecimal with fn output(self, logger) {
  let zero = @bigint.BigInt::from_int(0)
  let negative = self.coefficient < zero
  let digits = (if negative { -self.coefficient } else { self.coefficient }).to_string()
  let padded = if digits.length() <= self.scale {
    "0".repeat(self.scale - digits.length() + 1) + digits
  } else {
    digits
  }
  if negative {
    logger.write_char('-')
  }
  let point = padded.length() - self.scale
  logger.write_view(padded[:point])
  if self.scale > 0 {
    logger.write_char('.')
    logger.write_view(padded[point:])
  }
}

///|
pub extend XamlDecimal with Show::{to_string}

///|
/// The value of `x:TimeSpan`: a signed count of 100-nanosecond ticks, as `System.TimeSpan` holds.
#derive(Eq, Hash, Compare, Debug)
pub struct XamlTimeSpan {
  priv ticks : Int64
}

///|
pub fn XamlTimeSpan::new(ticks : Int64) -> XamlTimeSpan {
  { ticks, }
}

///|
pub fn XamlTimeSpan::ticks(self : XamlTimeSpan) -> Int64 {
  self.ticks
}

///|
/// What `x:Array` gives: the declared item type and the items (design D12, F7). The item type is
/// kept as declared, so saving writes it unchanged even when the array is empty or holds items of
/// derived types.
#derive(Debug)
pub struct XamlArray {
  item_type : @nodes.XamlTypeName
  items : ReadOnlyArray[@nodes.XamlValue]
}

///|
/// An array with a copy of `items`.
pub fn XamlArray::new(
  item_type : @nodes.XamlTypeName,
  items : ArrayView[@nodes.XamlValue],
) -> XamlArray {
  { item_type, items: ReadOnlyArray::from_array(items), }
}

///|
/// Arrays are equal when their item types and items are equal, NaN items included.
pub impl Eq for XamlArray with fn equal(self, other) {
  self.item_type == other.item_type &&
  @nodes.XamlValue::list(self.items[:]) ==
  @nodes.XamlValue::list(other.items[:])
}

///|
pub impl Hash for XamlArray with fn hash_combine(self, hasher) {
  hasher.combine(self.item_type)
  hasher.combine(@nodes.XamlValue::list(self.items[:]))
}

///|
/// The key of values that are equal when their contents are.
fn[T : Eq + Hash] value_key() -> @nodes.ObjectKey[T] {
  @nodes.ObjectKey::new(equal=(a, b) => a == b, hash=Hash::hash)
}

///|
let decimal_key : @nodes.ObjectKey[XamlDecimal] = value_key()

///|
let time_span_key : @nodes.ObjectKey[XamlTimeSpan] = value_key()

///|
let uri_key : @nodes.ObjectKey[XamlUri] = value_key()

///|
/// An `x:Decimal` value: a handle that compares by numeric value.
pub fn decimal_value(value : XamlDecimal) -> @nodes.XamlValue {
  Object(decimal_key.wrap(decimal_type, value))
}

///|
/// The decimal in a value that `decimal_value` made.
pub fn as_decimal(value : @nodes.XamlValue) -> XamlDecimal? {
  match value {
    Object(handle) => decimal_key.unwrap(handle)
    _ => None
  }
}

///|
/// An `x:TimeSpan` value: a handle that compares by ticks.
pub fn time_span_value(value : XamlTimeSpan) -> @nodes.XamlValue {
  Object(time_span_key.wrap(time_span_type, value))
}

///|
/// The time span in a value that `time_span_value` made.
pub fn as_time_span(value : @nodes.XamlValue) -> XamlTimeSpan? {
  match value {
    Object(handle) => time_span_key.unwrap(handle)
    _ => None
  }
}

///|
/// An `x:Uri` value: a handle that compares by text.
pub fn uri_value(value : XamlUri) -> @nodes.XamlValue {
  Object(uri_key.wrap(uri_type, value))
}

///|
/// The URI in a value that `uri_value` made.
pub fn as_uri(value : @nodes.XamlValue) -> XamlUri? {
  match value {
    Object(handle) => uri_key.unwrap(handle)
    _ => None
  }
}