// Invariant text rules of the .NET converters of the XAML language primitives (design D19).

///|
/// Whether `unit` is white space by .NET `char.IsWhiteSpace`, which `String.Trim` uses.
fn is_dotnet_white_space(unit : UInt16) -> Bool {
  let u = unit.to_int()
  (u >= 0x09 && u <= 0x0D) ||
  u == 0x20 ||
  u == 0x85 ||
  u == 0xA0 ||
  u == 0x1680 ||
  (u >= 0x2000 && u <= 0x200A) ||
  u == 0x2028 ||
  u == 0x2029 ||
  u == 0x202F ||
  u == 0x205F ||
  u == 0x3000
}

///|
/// `text` without the leading and trailing units that `drop` accepts.
fn trim_units(text : String, drop : (UInt16) -> Bool) -> String {
  let mut start = 0
  let mut end = text.length()
  while start < end && drop(text.code_unit_at(start)) {
    start += 1
  }
  while end > start && drop(text.code_unit_at(end - 1)) {
    end -= 1
  }
  if start == 0 && end == text.length() {
    text
  } else {
    text[start:end].to_owned()
  }
}

///|
/// .NET `String.Trim()`.
fn dotnet_trim(text : String) -> String {
  trim_units(text, is_dotnet_white_space)
}

///|
fn digit_value(unit : UInt16) -> UInt64 {
  (unit.to_int() - '0'.to_int()).to_uint64()
}

///|
fn hex_value(unit : UInt16) -> UInt64? {
  let u = unit.to_int()
  if unit >= '0' && unit <= '9' {
    Some((u - '0'.to_int()).to_uint64())
  } else if unit >= 'a' && unit <= 'f' {
    Some((u - 'a'.to_int() + 10).to_uint64())
  } else if unit >= 'A' && unit <= 'F' {
    Some((u - 'A'.to_int() + 10).to_uint64())
  } else {
    None
  }
}

///|
/// The width and signedness of an integer type.
priv struct IntegerKind {
  label : String
  bits : Int32
  signed : Bool
}

///|
/// The largest magnitude of a value of `kind`: the maximum, or for a negative value the magnitude of
/// the minimum.
fn IntegerKind::limit(self : IntegerKind, negative : Bool) -> UInt64 {
  if self.signed {
    let half = 1UL << (self.bits - 1)
    if negative {
      half
    } else {
      half - 1
    }
  } else if negative {
    0
  } else if self.bits == 64 {
    0xFFFF_FFFF_FFFF_FFFFUL
  } else {
    (1UL << self.bits) - 1
  }
}

///|
/// A sign and decimal digits, as `NumberStyles.Integer` reads trimmed invariant text. The result is
/// the value as 64-bit two's complement bits, sign-extended for signed kinds.
fn parse_decimal_integer(
  text : String,
  kind : IntegerKind,
) -> UInt64 raise ValueError {
  let length = text.length()
  let mut i = 0
  let mut negative = false
  if i < length && (text.code_unit_at(i) == '+' || text.code_unit_at(i) == '-') {
    negative = text.code_unit_at(i) == '-'
    i += 1
  }
  if i >= length {
    raise ValueError("\"\{text}\" is not a valid \{kind.label}")
  }
  let limit = kind.limit(negative)
  let mut magnitude = 0UL
  while i < length {
    let unit = text.code_unit_at(i)
    if !is_ascii_digit(unit) {
      raise ValueError("\"\{text}\" is not a valid \{kind.label}")
    }
    let digit = digit_value(unit)
    if digit > limit || magnitude > (limit - digit) / 10 {
      raise ValueError(
        "\"\{text}\" is outside the range of \{kind.label} (too large or too small)",
      )
    }
    magnitude = magnitude * 10 + digit
    i += 1
  }
  if negative {
    0UL - magnitude
  } else {
    magnitude
  }
}

///|
/// Hexadecimal digits, as `Convert.ToInt32(text, 16)` and its siblings read them: the bits of the
/// kind's width, so `FFFFFFFF` is `-1` for `Int32`.
fn parse_hex_integer(
  text : String,
  kind : IntegerKind,
) -> UInt64 raise ValueError {
  if text.is_empty() {
    raise ValueError("\"\{text}\" is not a valid \{kind.label}")
  }
  let mut value = 0UL
  for i in 0..> (kind.bits - 4) != 0UL {
      raise ValueError("\"\{text}\" is outside the range of \{kind.label}")
    }
    value = value * 16 + digit
  }
  if kind.signed && kind.bits < 64 && value >> (kind.bits - 1) != 0 {
    // Sign-extend the width's two's complement bits.
    value | (0xFFFF_FFFF_FFFF_FFFFUL << kind.bits)
  } else {
    value
  }
}

///|
/// Integer text as .NET's `BaseNumberConverter` reads it: trimmed, then `#`, `0x` or `&h` and
/// hexadecimal digits, else a sign and decimal digits.
fn parse_integer_text(
  text : String,
  kind : IntegerKind,
) -> UInt64 raise ValueError {
  let trimmed = dotnet_trim(text)
  let lower = trimmed.to_lower()
  if lower.has_prefix("#") {
    parse_hex_integer(lower[1:].to_owned(), kind)
  } else if lower.has_prefix("0x") || lower.has_prefix("&h") {
    parse_hex_integer(lower[2:].to_owned(), kind)
  } else {
    parse_decimal_integer(trimmed, kind)
  }
}

///|
let byte_kind : IntegerKind = { label: "x:Byte", bits: 8, signed: false, }

///|
let int16_kind : IntegerKind = { label: "x:Int16", bits: 16, signed: true, }

///|
let int32_kind : IntegerKind = { label: "x:Int32", bits: 32, signed: true, }

///|
let int64_kind : IntegerKind = { label: "x:Int64", bits: 64, signed: true, }

///|
/// The parts of floating-point text: sign, significant digits and the decimal exponent of the first
/// digit's position, so that the value is `0.DIGITS × 10^scale`.
priv struct DecimalText {
  negative : Bool
  digits : String
  /// The number of digits after the point, minus the exponent.
  fraction : Int32
}

///|
/// `[sign] (digits [. digits] | . digits) [(e|E) [sign] digits]`, as `NumberStyles.Float` reads
/// trimmed invariant text, or `None`.
fn split_float_text(text : String) -> DecimalText? {
  let length = text.length()
  let mut i = 0
  let mut negative = false
  if i < length && (text.code_unit_at(i) == '+' || text.code_unit_at(i) == '-') {
    negative = text.code_unit_at(i) == '-'
    i += 1
  }
  let digits = StringBuilder()
  let mut count = 0
  let mut fraction = 0
  while i < length && is_ascii_digit(text.code_unit_at(i)) {
    digits.write_char(text.code_unit_at(i).to_int().unsafe_to_char())
    count += 1
    i += 1
  }
  if i < length && text.code_unit_at(i) == '.' {
    i += 1
    while i < length && is_ascii_digit(text.code_unit_at(i)) {
      digits.write_char(text.code_unit_at(i).to_int().unsafe_to_char())
      count += 1
      fraction += 1
      i += 1
    }
  }
  if count == 0 {
    return None
  }
  if i < length && (text.code_unit_at(i) == 'e' || text.code_unit_at(i) == 'E') {
    i += 1
    let mut exponent_negative = false
    if i < length &&
      (text.code_unit_at(i) == '+' || text.code_unit_at(i) == '-') {
      exponent_negative = text.code_unit_at(i) == '-'
      i += 1
    }
    let start = i
    let mut exponent = 0
    while i < length && is_ascii_digit(text.code_unit_at(i)) {
      // Clamp: any exponent beyond the range of every type saturates.
      if exponent < 100_000 {
        exponent = exponent * 10 + digit_value(text.code_unit_at(i)).to_int()
      }
      i += 1
    }
    if i == start {
      return None
    }
    fraction = if exponent_negative {
      fraction + exponent
    } else {
      fraction - exponent
    }
  }
  if i != length {
    return None
  }
  Some({ negative, digits: digits.to_string(), fraction, })
}

///|
/// Floating-point text as `Double.Parse(text, NumberStyles.Float, InvariantCulture)` reads it after
/// `DoubleConverter` trims it: `Infinity`, `-Infinity` and `NaN` ignoring case and with a sign, and
/// overflow to an infinity.
fn parse_double_text(text : String, label : String) -> Double raise ValueError {
  let trimmed = dotnet_trim(text)
  match trimmed.to_lower() {
    "infinity" | "+infinity" => return @double.infinity
    "-infinity" => return @double.neg_infinity
    "nan" | "+nan" | "-nan" => return @double.not_a_number
    _ => ()
  }
  guard split_float_text(trimmed) is Some(parts) else {
    raise ValueError("\"\{text}\" is not a valid \{label}")
  }
  let sign = if parts.negative { "-" } else { "" }
  let normalized = "\{sign}\{parts.digits}e\{-parts.fraction}"
  @string.parse_double(normalized) catch {
    // The syntax is checked, so the only failure left is overflow.
    _ => if parts.negative { @double.neg_infinity } else { @double.infinity }
  }
}

///|
/// The shortest round-trip digits of a finite nonzero value printed by MoonBit, as significant
/// digits and the scale of `0.DIGITS × 10^scale`.
fn shortest_digits(repr : String) -> (String, Int32) {
  let text = if repr.has_prefix("-") { repr[1:].to_owned() } else { repr }
  let (mantissa, exponent) = match text.find("e") {
    Some(e) =>
      (
        text[:e].to_owned(),
        @string.parse_int(text[e + 1:].to_owned()) catch {
          _ => 0
        },
      )
    None => (text, 0)
  }
  let (whole, fraction) = match mantissa.find(".") {
    Some(p) => (mantissa[:p].to_owned(), mantissa[p + 1:].to_owned())
    None => (mantissa, "")
  }
  let all = whole + fraction
  let mut first = 0
  while first < all.length() && all.code_unit_at(first) == '0' {
    first += 1
  }
  let mut last = all.length()
  while last > first && all.code_unit_at(last - 1) == '0' {
    last -= 1
  }
  let digits = all[first:last].to_owned()
  (digits, whole.length() - first + exponent)
}

///|
/// A finite value as .NET Core's shortest round-trip `ToString()` writes it: plain digits while the
/// decimal point is within `max(digit count, precision)` digits and the scale is at least -3, else
/// `d.dddE+XX`.
fn format_general(
  negative : Bool,
  digits : String,
  scale : Int32,
  precision : Int32,
) -> String {
  let buffer = StringBuilder()
  if negative {
    buffer.write_char('-')
  }
  if digits.is_empty() {
    buffer.write_char('0')
    return buffer.to_string()
  }
  let max_digits = if digits.length() > precision {
    digits.length()
  } else {
    precision
  }
  if scale > max_digits || scale < -3 {
    buffer.write_view(digits[:1])
    if digits.length() > 1 {
      buffer.write_char('.')
      buffer.write_view(digits[1:])
    }
    let exponent = scale - 1
    buffer.write_char('E')
    buffer.write_char(if exponent < 0 { '-' } else { '+' })
    let magnitude = (if exponent < 0 { -exponent } else { exponent }).to_string()
    if magnitude.length() < 2 {
      buffer.write_char('0')
    }
    buffer.write_string(magnitude)
  } else if scale <= 0 {
    buffer.write_string("0.")
    buffer.write_string("0".repeat(-scale))
    buffer.write_string(digits)
  } else if scale >= digits.length() {
    buffer.write_string(digits)
    buffer.write_string("0".repeat(scale - digits.length()))
  } else {
    buffer.write_view(digits[:scale])
    buffer.write_char('.')
    buffer.write_view(digits[scale:])
  }
  buffer.to_string()
}

///|
/// A double as invariant `Double.ToString()` writes it in .NET Core 3.0 and later.
fn format_double(value : Double) -> String {
  if value.is_nan() {
    return "NaN"
  }
  if value == @double.infinity {
    return "Infinity"
  }
  if value == @double.neg_infinity {
    return "-Infinity"
  }
  let negative = value.reinterpret_as_int64() < 0L
  if value == 0.0 {
    return if negative { "-0" } else { "0" }
  }
  let (digits, scale) = shortest_digits(value.to_string())
  format_general(negative, digits, scale, 15)
}

///|
/// A single as invariant `Single.ToString()` writes it in .NET Core 3.0 and later.
fn format_single(value : Float) -> String {
  let wide = value.to_double()
  if wide.is_nan() {
    return "NaN"
  }
  if wide == @double.infinity {
    return "Infinity"
  }
  if wide == @double.neg_infinity {
    return "-Infinity"
  }
  let negative = wide.reinterpret_as_int64() < 0L
  if wide == 0.0 {
    return if negative { "-0" } else { "0" }
  }
  let (digits, scale) = shortest_digits(value.to_string())
  format_general(negative, digits, scale, 7)
}

///|
/// `Boolean.Parse`: `True` or `False` ignoring case, with white space and U+0000 trimmed.
fn parse_boolean_text(text : String) -> Bool raise ValueError {
  match trim_units(text, u => is_dotnet_white_space(u) || u == 0).to_lower() {
    "true" => true
    "false" => false
    _ => raise ValueError("\"\{text}\" is not a valid x:Boolean")
  }
}

///|
/// `CharConverter`: text longer than one unit is trimmed; one unit is the character, empty text is
/// U+0000, and more is an error.
fn parse_char_text(text : String) -> UInt16 raise ValueError {
  let trimmed = if text.length() > 1 { dotnet_trim(text) } else { text }
  match trimmed.length() {
    0 => 0
    1 => trimmed.code_unit_at(0)
    _ =>
      raise ValueError(
        "\"\{text}\" is not a valid x:Char: it must be exactly one UTF-16 code unit",
      )
  }
}

///|
/// `CharConverter` to text: U+0000 is empty text.
fn format_char(unit : UInt16) -> String {
  if unit == 0 {
    ""
  } else {
    let buffer = StringBuilder()
    buffer.write_char(unit.to_int().unsafe_to_char())
    buffer.to_string()
  }
}

///|
/// The number of the first `count` decimal digits of `digits`, rounded half to even for the others.
fn round_digits(digits : StringView, count : Int32) -> @bigint.BigInt {
  let one = @bigint.BigInt::from_int(1)
  let kept = if count == 0 {
    @bigint.BigInt::from_int(0)
  } else {
    try! @string.parse_bigint(digits[:count])
  }
  let up = match digits[count:] {
    [] | ['0'..<='4', ..] => false
    ['5', .. rest] =>
      rest.iter().any(digit => digit != '0') || (kept & one) == one
    _ => true
  }
  if up {
    kept + one
  } else {
    kept
  }
}

///|
/// `Decimal.Parse(text, NumberStyles.Float, InvariantCulture)` after `DecimalConverter` trims it: the
/// scale is at most 28, the coefficient is below 2^96, and the digits that do not fit are rounded once,
/// half to even.
fn parse_decimal_text(text : String) -> XamlDecimal raise ValueError {
  guard split_float_text(dotnet_trim(text)) is Some(parts) else {
    raise ValueError("\"\{text}\" is not a valid x:Decimal")
  }
  let digits = parts.digits.trim_start(chars="0")
  let scale = parts.fraction
  let zero = @bigint.BigInt::from_int(0)
  if digits.is_empty() {
    return XamlDecimal::new(zero, scale.clamp(min=0, max=28))
  }
  // The number of digits before the point. 2^96 has 29.
  let whole = digits.length() - scale
  if whole <= 29 {
    let digits = if scale < 0 {
      digits.to_owned() + "0".repeat(-scale)
    } else {
      digits.to_owned()
    }
    let most = digits.length().min(29).min(whole + 28)
    if most < 0 {
      return XamlDecimal::new(zero, 28)
    }
    // 29 digits can be too many, also because they are rounded to 2^96. 28 always fit.
    for count = most; count >= whole; count = count - 1 {
      let coefficient = round_digits(digits, count)
      if coefficient < decimal_limit {
        return XamlDecimal::new(
          if parts.negative {
            -coefficient
          } else {
            coefficient
          },
          count - whole,
        )
      }
    }
  }
  raise ValueError("\"\{text}\" is outside the range of x:Decimal")
}

///|
let ticks_per_second : Int64 = 10_000_000L

///|
let ticks_per_minute : Int64 = ticks_per_second * 60L

///|
let ticks_per_hour : Int64 = ticks_per_minute * 60L

///|
let ticks_per_day : Int64 = ticks_per_hour * 24L

///|
/// Decimal digits of a time span component, or `None`.
fn time_component(text : StringView) -> Int64? {
  if text.is_empty() || text.length() > 10 {
    return None
  }
  let mut value = 0L
  for c in text.iter() {
    if c < '0' || c > '9' {
      return None
    }
    value = value * 10L + (c.to_int() - '0'.to_int()).to_int64()
  }
  Some(value)
}

///|
/// `TimeSpan.Parse(text, InvariantCulture)` after `TimeSpanConverter` trims it: `[-]d`, or
/// `[-][d(.|:)]h:m[:s[.f]]` with hours below 24, minutes and seconds below 60, one to seven
/// fraction digits and the total within the tick range.
fn parse_time_span_text(text : String) -> XamlTimeSpan raise ValueError {
  let invalid = () => ValueError("\"\{text}\" is not a valid x:TimeSpan")
  let overflow = () => {
    ValueError("\"\{text}\" is outside the range of x:TimeSpan")
  }
  let trimmed = dotnet_trim(text)
  let mut body : StringView = trimmed
  let negative = body.has_prefix("-")
  if negative {
    body = body[1:]
  }
  let parts = body.split(":").collect()
  let mut days = 0L
  let mut hours = 0L
  let mut minutes = 0L
  let mut seconds = 0L
  let mut fraction = 0L
  match parts.length() {
    1 => {
      guard time_component(parts[0]) is Some(d) else { raise invalid() }
      days = d
    }
    2 | 3 | 4 => {
      let mut first = 0
      // The first component may hold days: `d.h` or, with four components, `d:h`.
      if parts.length() == 4 {
        guard time_component(parts[0]) is Some(d) else { raise invalid() }
        days = d
        first = 1
      }
      let head = parts[first]
      match head.find(".") {
        Some(p) if parts.length() < 4 => {
          guard time_component(head[:p]) is Some(d) else { raise invalid() }
          guard time_component(head[p + 1:]) is Some(h) else { raise invalid() }
          days = d
          hours = h
        }
        _ => {
          guard time_component(head) is Some(h) else { raise invalid() }
          hours = h
        }
      }
      guard time_component(parts[first + 1]) is Some(m) else { raise invalid() }
      minutes = m
      if first + 2 < parts.length() {
        let last = parts[first + 2]
        let (whole, digits) = match last.find(".") {
          Some(p) => (last[:p], Some(last[p + 1:]))
          None => (last, None)
        }
        guard time_component(whole) is Some(s) else { raise invalid() }
        seconds = s
        if digits is Some(digits) {
          guard time_component(digits) is Some(f) else { raise invalid() }
          if digits.length() > 7 {
            raise overflow()
          }
          fraction = f
          for _ in digits.length()..<7 {
            fraction = fraction * 10L
          }
        }
      } else if parts.length() == 4 {
        raise invalid()
      }
    }
    _ => raise invalid()
  }
  if hours > 23L || minutes > 59L || seconds > 59L {
    raise overflow()
  }
  // 10675199 days is the largest whole day count within the tick range.
  if days > 10675199L {
    raise overflow()
  }
  // The negative range has one tick more, so the sum is negative, as in `format_time_span`. A sum outside
  // the range wraps around once.
  let ticks = -(days * ticks_per_day) -
    hours * ticks_per_hour -
    minutes * ticks_per_minute -
    seconds * ticks_per_second -
    fraction
  let result = if negative { ticks } else { -ticks }
  if ticks > 0L || (!negative && result < 0L) {
    raise overflow()
  }
  XamlTimeSpan::new(result)
}

///|
fn two_digits(value : Int64) -> String {
  if value < 10L {
    "0\{value}"
  } else {
    value.to_string()
  }
}

///|
/// The invariant `c` format of a time span: `[-][d.]hh:mm:ss[.fffffff]`.
fn format_time_span(span : XamlTimeSpan) -> String {
  let ticks = span.ticks()
  let buffer = StringBuilder()
  // The minimum tick count has no positive counterpart, so work with the negative magnitude.
  let negative = ticks < 0L
  let magnitude = if negative { ticks } else { -ticks }
  let days = -(magnitude / ticks_per_day)
  let rest = -(magnitude % ticks_per_day)
  let hours = rest / ticks_per_hour
  let minutes = rest % ticks_per_hour / ticks_per_minute
  let seconds = rest % ticks_per_minute / ticks_per_second
  let fraction = rest % ticks_per_second
  if negative {
    buffer.write_char('-')
  }
  if days != 0L {
    buffer.write_string("\{days}.")
  }
  buffer.write_string(
    "\{two_digits(hours)}:\{two_digits(minutes)}:\{two_digits(seconds)}",
  )
  if fraction != 0L {
    let digits = fraction.to_string()
    buffer.write_char('.')
    buffer.write_string("0".repeat(7 - digits.length()))
    buffer.write_string(digits)
  }
  buffer.to_string()
}