// The keys of described types, and the codecs of types with a text and of enumerations (design F2 of add-xaml-codecs).

///|
/// The XAML name of `T` and the identity of its values. Keep it in a top-level `let`, because each call of `XamlKey::new` gives
/// another identity.
pub struct XamlKey[T] {
  priv type_name : @nodes.XamlTypeName
  /// The key of values that are objects. Its identity is that of this key.
  priv objects : @nodes.ObjectKey[T]
  /// The key of values that are the same when they are equal.
  priv values : @nodes.ObjectKey[T]
  /// What `objects` makes the hash from.
  priv leaves : Ref[Array[(T) -> @nodes.XamlValue raise]]
  /// How `values` compares.
  priv equal : Ref[(T, T) -> Bool]
  priv context : Ref[@schema.SchemaContext?]
}

///|
/// The key of the XAML type `name` in the namespace `namespace_uri`.
pub fn[T] XamlKey::new(namespace_uri : String, name : String) -> XamlKey[T] {
  let leaves : Ref[Array[(T) -> @nodes.XamlValue raise]] = Ref([])
  let equal : Ref[(T, T) -> Bool] = Ref((_, _) => false)
  {
    type_name: @nodes.XamlTypeName::new(namespace_uri, name),
    objects: @nodes.ObjectKey::new(hash=value => {
      let hasher = Hasher()
      for leaf in leaves.val {
        // Writing the member reports the error of a value that XAML cannot hold.
        hasher.combine(leaf(value)) catch {
          _ => ()
        }
      }
      hasher.finalize()
    }),
    values: @nodes.ObjectKey::new(equal=(a, b) => (equal.val)(a, b)),
    leaves,
    equal,
    context: Ref(None),
  }
}

///|
/// Register the type with the definition that `definition` gives, unless it is registered.
fn[T] XamlKey::register(
  self : XamlKey[T],
  registry : Registry,
  definition : () -> @schema.XamlTypeDefinition,
) -> Unit {
  let id = self.objects.id()
  match registry.keys.get(self.type_name) {
    None => {
      // Before the definition, in which the type can have itself.
      registry.keys[self.type_name] = id
      let { choice_depth, .. } = registry
      registry.choice_depth = 0
      ignore(registry.builder.add_type(definition()))
      registry.choice_depth = choice_depth
    }
    Some(other) =>
      if other != id {
        registry.add_problem(
          "\{self.type_name} has two keys: each key needs a name of its own and a top-level `let`",
        )
      }
  }
}

///|
/// Describe a type whose values each have one text, such as `1,2`. `print` gives the text, and `parse` the value or an error.
/// Equal values are the same in XAML, so they are never written as references.
pub fn[T : Eq] XamlKey::text(
  self : XamlKey[T],
  parse~ : (String) -> T raise,
  print~ : (T) -> String raise,
) -> XamlCodec[T] {
  let { type_name, values, context, .. } = self
  self.equal.val = (a, b) => a == b
  fn from_xaml(value : @nodes.XamlValue) -> T raise {
    guard value is @nodes.XamlValue::Object(handle) &&
      values.unwrap(handle) is Some(found) else {
      raise not_a(value, type_name)
    }
    found
  }
  {
    type_name,
    value_types: () => [type_name],
    nullable: false,
    missing: None,
    is_leaf: false,
    to_label: Some(print),
    problem: None,
    register: registry => {
      self.register(registry, () => {
        let type_converter = @schema.TypeConverter::from_text(
          (_, text) => Object(values.wrap(type_name, parse(text))),
          format=(_, value) => print(from_xaml(value)),
        )
        @schema.XamlTypeDefinition::new(
          type_name.namespace_uri,
          type_name.name,
          type_converter~,
        ).object_key(values)
      })
    },
    to_xaml: value => Object(values.wrap(type_name, value)),
    from_xaml,
    check: value => ignore(from_xaml(value)),
    context,
  }
}

///|
/// Describe an enum without payloads by the names of its values.
///
/// The text rules are those of .NET `Enum.Parse`. So a text can also be the position of a value in `names`, and `Low, High` is
/// the number that has the bits of both positions. A number without a name is an error.
pub fn[T : Eq] XamlKey::enumeration(
  self : XamlKey[T],
  names : ArrayView[(String, T)],
) -> XamlCodec[T] {
  let { type_name, context, .. } = self
  let position = (value : T) => {
    guard names.search_by(entry => entry.1 == value) is Some(i) else {
      raise @schema.ValueError("the value has no name in \{type_name}")
    }
    i
  }
  fn from_xaml(value : @nodes.XamlValue) -> T raise {
    guard @schema.as_enum_value(value) is Some(found) &&
      found.type_name == type_name else {
      raise not_a(value, type_name)
    }
    let number = found.bits.reinterpret_as_int64()
    guard number >= 0L && number < names.length().to_int64() else {
      raise @schema.ValueError("\{type_name} has no value \{number}")
    }
    names[number.to_int()].1
  }
  {
    type_name,
    value_types: () => [type_name],
    nullable: false,
    missing: None,
    is_leaf: true,
    to_label: Some(value => names[position(value)].0),
    problem: None,
    register: registry => {
      self.register(registry, () => {
        let numbers = names.mapi((i, entry) => (entry.0, i.to_int64()))
        @schema.XamlTypeDefinition::new(type_name.namespace_uri, type_name.name).enumeration(
          Int32,
          numbers,
        )
      })
    },
    to_xaml: value => {
      let bits = position(value).to_int64().reinterpret_as_uint64()
      @schema.enum_value({ type_name, bits, })
    },
    from_xaml,
    check: value => ignore(from_xaml(value)),
    context,
  }
}