// The built-in type converters and value serializers of the XAML language types (design D19).

///|
/// A converter from text with `parse` and to text with `format`, which gives `None` for a value of
/// another type.
fn primitive_converter(
  label : String,
  parse : (String) -> @nodes.XamlValue raise,
  format : (@nodes.XamlValue) -> String?,
) -> TypeConverter {
  TypeConverter::from_text((_, text) => parse(text), format=(_, value) => {
    match format(value) {
      Some(text) => text
      None => raise ValueError("the value is not a value of \{label}")
    }
  })
}

///|
/// `x:String`: strings pass through.
let string_converter : TypeConverter = TypeConverter::new(
  convert_from=(_, value) => {
    guard value is String(_) else {
      raise ValueError("the value is not a value of x:String")
    }
    value
  },
  convert_to=(_, value, destination) => {
    guard destination is Text && value is String(_) else {
      raise ValueError("the value is not a value of x:String")
    }
    value
  },
)

///|
/// `x:Object`: every value passes through unchanged, as System.Xaml's object converter does.
let object_converter : TypeConverter = TypeConverter::new(
  convert_from=(_, value) => value,
  can_convert_from=(_, _) => true,
)

///|
/// The built-in value serializer of `x:String`.
let string_serializer : ValueSerializer = ValueSerializer::new(
  convert_to_string=(_, value) => {
    guard value is String(text) else {
      raise ValueError("the value is not a value of x:String")
    }
    text
  },
  can_convert_to_string=(_, value) => value is String(_),
  convert_from_string=(_, text) => String(text),
)

///|
fn integer_converter(
  kind : IntegerKind,
  make : (UInt64) -> @nodes.XamlValue,
  format : (@nodes.XamlValue) -> String?,
) -> TypeConverter {
  primitive_converter(
    kind.label,
    text => make(parse_integer_text(text, kind)),
    format,
  )
}

///|
/// The built-in converter of each XAML language primitive, by type name.
fn primitive_converters() -> Map[String, TypeConverter] {
  Map([
    ("String", string_converter),
    ("Object", object_converter),
    (
      "Boolean",
      primitive_converter("x:Boolean", text => Bool(parse_boolean_text(text)), value => {
        match value {
          Bool(true) => Some("True")
          Bool(false) => Some("False")
          _ => None
        }
      }),
    ),
    (
      "Byte",
      integer_converter(byte_kind, bits => Byte(bits.to_byte()), value => {
        match value {
          Byte(b) => Some(b.to_int().to_string())
          _ => None
        }
      }),
    ),
    (
      "Int16",
      integer_converter(
        int16_kind,
        bits => Int16(Int16::from_int64(bits.reinterpret_as_int64())),
        value => {
          match value {
            Int16(i) => Some(i.to_string())
            _ => None
          }
        },
      ),
    ),
    (
      "Int32",
      integer_converter(
        int32_kind,
        bits => Int(bits.reinterpret_as_int64().to_int()),
        value => {
          match value {
            Int(i) => Some(i.to_string())
            _ => None
          }
        },
      ),
    ),
    (
      "Int64",
      integer_converter(
        int64_kind,
        bits => Int64(bits.reinterpret_as_int64()),
        value => {
          match value {
            Int64(i) => Some(i.to_string())
            _ => None
          }
        },
      ),
    ),
    (
      "Double",
      primitive_converter(
        "x:Double",
        text => Double(parse_double_text(text, "x:Double")),
        value => {
          match value {
            Double(d) => Some(format_double(d))
            _ => None
          }
        },
      ),
    ),
    (
      "Single",
      primitive_converter(
        "x:Single",
        // The text is read as a double and then rounded to a single, which can differ from .NET's
        // direct rounding in the last unit only for inputs of more than 17 significant digits.
        text => Single(Float::from_double(parse_double_text(text, "x:Single"))),
        value => {
          match value {
            Single(f) => Some(format_single(f))
            _ => None
          }
        },
      ),
    ),
    (
      "Char",
      primitive_converter("x:Char", text => Char(parse_char_text(text)), value => {
        match value {
          Char(unit) => Some(format_char(unit))
          _ => None
        }
      }),
    ),
    (
      "Decimal",
      primitive_converter(
        "x:Decimal",
        text => decimal_value(parse_decimal_text(text)),
        value => as_decimal(value).map(d => "\{d}"),
      ),
    ),
    (
      "TimeSpan",
      primitive_converter(
        "x:TimeSpan",
        text => time_span_value(parse_time_span_text(text)),
        value => as_time_span(value).map(format_time_span),
      ),
    ),
    (
      "Uri",
      primitive_converter("x:Uri", text => uri_value(XamlUri::parse(text)), value => {
        as_uri(value).map(u => u.text())
      }),
    ),
    ("TypeValue", type_value_converter),
  ])
}

///|
/// The converter of type values (2F9), as System.Xaml's `TypeTypeConverter`: from `prefix:Name`
/// text, type arguments included, through the context's `resolve_type`, and to that text through
/// its `lookup_prefix`. Both directions need the context.
let type_value_converter : TypeConverter = TypeConverter::new(
  convert_from=(context, value) => {
    guard value is String(text) else {
      raise ValueError("a type value converts only from text")
    }
    guard context.bind(c => c.resolve_type) is Some(resolve_type) else {
      raise ValueError(
        "converting the type name \"\{text}\" needs a context that resolves types",
      )
    }
    guard resolve_type(text) is Some(name) else {
      raise ValueError("the type \"\{text}\" cannot be resolved")
    }
    type_value(name)
  },
  convert_to=(context, value, destination) => {
    guard destination is Text else {
      raise ValueError("a type value converts only to text")
    }
    guard as_type_name(value) is Some(name) else {
      raise ValueError("the value is not a type value")
    }
    guard context.lookup_prefix is Some(lookup_prefix) else {
      raise ValueError(
        "writing the type name \{name} needs a context that looks up prefixes",
      )
    }
    String(name.to_text(namespace_uri => Some(lookup_prefix(namespace_uri))))
  },
)