// The codecs of the types of the XAML language and of optional values.

///|
/// The context of the values that need no described type.
let language_context : Ref[@schema.SchemaContext?] = Ref(None)

///|
/// The codec of a type of the XAML language.
fn[T] language_codec(
  type_name : @nodes.XamlTypeName,
  from_xaml : (@nodes.XamlValue) -> T raise,
  to_xaml : (T) -> @nodes.XamlValue raise,
  to_label : (T) -> String,
) -> XamlCodec[T] {
  {
    type_name,
    value_types: () => [type_name],
    nullable: false,
    missing: None,
    is_leaf: true,
    to_label: Some(value => to_label(value)),
    problem: None,
    register: _ => (),
    to_xaml,
    from_xaml,
    check: value => ignore(from_xaml(value)),
    context: language_context,
  }
}

///|
/// The same, with a function that gives `None` for a value of another type.
fn[T : Show] simple_codec(
  type_name : @nodes.XamlTypeName,
  read : (@nodes.XamlValue) -> T?,
  write : (T) -> @nodes.XamlValue,
) -> XamlCodec[T] {
  language_codec(
    type_name,
    value => {
      guard read(value) is Some(found) else { raise not_a(value, type_name) }
      found
    },
    value => write(value),
    value => value.to_string(),
  )
}

///|
/// `x:Boolean`.
pub impl Xaml for Bool with fn xaml_codec() {
  simple_codec(
    @schema.boolean_type,
    value => if value is Bool(b) { Some(b) } else { None },
    b => Bool(b),
  )
}

///|
/// `x:Byte`.
pub impl Xaml for Byte with fn xaml_codec() {
  simple_codec(
    @schema.byte_type,
    value => if value is Byte(b) { Some(b) } else { None },
    b => Byte(b),
  )
}

///|
/// `x:Int16`.
pub impl Xaml for Int16 with fn xaml_codec() {
  simple_codec(
    @schema.int16_type,
    value => if value is Int16(n) { Some(n) } else { None },
    n => Int16(n),
  )
}

///|
/// `x:Int32`.
pub impl Xaml for Int32 with fn xaml_codec() {
  simple_codec(
    @schema.int32_type,
    value => if value is Int(n) { Some(n) } else { None },
    n => Int(n),
  )
}

///|
/// `x:Int64`.
pub impl Xaml for Int64 with fn xaml_codec() {
  simple_codec(
    @schema.int64_type,
    value => if value is Int64(n) { Some(n) } else { None },
    n => Int64(n),
  )
}

///|
/// `x:Single`.
pub impl Xaml for Float with fn xaml_codec() {
  simple_codec(
    @schema.single_type,
    value => if value is Single(f) { Some(f) } else { None },
    f => Single(f),
  )
}

///|
/// `x:Double`.
pub impl Xaml for Double with fn xaml_codec() {
  simple_codec(
    @schema.double_type,
    value => if value is Double(d) { Some(d) } else { None },
    d => Double(d),
  )
}

///|
/// `x:String`.
pub impl Xaml for String with fn xaml_codec() {
  simple_codec(
    @schema.string_type,
    value => if value is String(s) { Some(s) } else { None },
    s => String(s),
  )
}

///|
/// `x:Char`, which is one UTF-16 code unit. So half of a surrogate pair cannot be read, and a character above U+FFFF cannot be
/// written.
pub impl Xaml for Char with fn xaml_codec() {
  language_codec(
    @schema.char_type,
    value => {
      guard value is Char(unit) else { raise not_a(value, @schema.char_type) }
      guard unit.to_int().to_char() is Some(c) else {
        raise @schema.ValueError("half of a surrogate pair is not a character")
      }
      c
    },
    c => {
      guard c.to_int() <= 0xFFFF else {
        raise @schema.ValueError(
          "\"\{c}\" is two UTF-16 code units, and an x:Char is one",
        )
      }
      Char(c.to_int().to_uint16())
    },
    c => c.to_string(),
  )
}

///|
/// `x:Decimal`.
pub impl Xaml for @schema.XamlDecimal with fn xaml_codec() {
  simple_codec(@schema.decimal_type, @schema.as_decimal, @schema.decimal_value)
}

///|
/// `x:TimeSpan`.
pub impl Xaml for @schema.XamlTimeSpan with fn xaml_codec() {
  language_codec(
    @schema.time_span_type,
    value => {
      guard @schema.as_time_span(value) is Some(found) else {
        raise not_a(value, @schema.time_span_type)
      }
      found
    },
    value => @schema.time_span_value(value),
    value => "\{value.ticks()} ticks",
  )
}

///|
/// `x:Uri`.
pub impl Xaml for @schema.XamlUri with fn xaml_codec() {
  simple_codec(@schema.uri_type, @schema.as_uri, @schema.uri_value)
}

///|
/// `None` is null in XAML, and what a member has that the document does not give.
pub impl[T : Xaml] Xaml for T? with fn xaml_codec() {
  let some : XamlCodec[T] = Xaml::xaml_codec()
  let problem = if some.nullable {
    Some(
      "an optional value cannot be optional again, because XAML has one null",
    )
  } else {
    some.problem
  }
  {
    type_name: some.type_name,
    value_types: some.value_types,
    nullable: true,
    missing: Some(None),
    is_leaf: some.is_leaf,
    to_label: None,
    problem,
    register: some.register,
    to_xaml: value => {
      match value {
        Some(value) => (some.to_xaml)(value)
        None => Null
      }
    },
    from_xaml: value => {
      if value is Null {
        None
      } else {
        Some((some.from_xaml)(value))
      }
    },
    check: value => if !(value is Null) { (some.check)(value) },
    context: some.context,
  }
}