// Codecs: descriptions of MoonBit types, from which values are read from XAML documents and written as them (design F1 to F9 of
// add-xaml-codecs).

///|
/// A type whose values XAML documents can hold. An implementation describes the type with an `XamlKey` in a top-level `let`.
pub(open) trait Xaml {
  /// The codec of the type.
  fn xaml_codec() -> XamlCodec[Self]
}

///|
/// How values of `T` become XAML, and how they are created from it. `XamlKey` and `XamlCodec::choice` make codecs.
pub struct XamlCodec[T] {
  /// The XAML type of a member that holds such values.
  priv type_name : @nodes.XamlTypeName
  /// The XAML types of the values. It is known when the codec is registered.
  priv value_types : () -> Array[@nodes.XamlTypeName]
  /// Whether null is a value.
  priv nullable : Bool
  /// What a member without a default has when the document does not give it. Without it the member is required.
  priv missing : T?
  /// Whether the XAML value has a quick hash that does not reach other objects.
  priv is_leaf : Bool
  /// The text of a value, if every value has one, as the key of a map needs.
  priv to_label : ((T) -> String raise)?
  /// Why no place can have such values.
  priv problem : String?
  /// Register the XAML types that the values need.
  priv register : (Registry) -> Unit
  priv to_xaml : (T) -> @nodes.XamlValue raise
  /// The value for a XAML value that passes `check`. An object has ended.
  priv from_xaml : (@nodes.XamlValue) -> T raise
  /// Raise an error for a XAML value that stands for no value of `T`. An object need not have its value yet.
  priv check : (@nodes.XamlValue) -> Unit raise
  /// The context with the types that `register` gives, after its first use.
  priv context : Ref[@schema.SchemaContext?]
}

///|
/// What is wrong in the descriptions of the types that `from_text` or `to_text` needs.
#derive(Eq, Debug)
pub(all) suberror CodecError {
  /// Every problem, each with the XAML type that it is about.
  WrongDescription(problems~ : ReadOnlyArray[String])
}

///|
pub fn CodecError::message(self : CodecError) -> String {
  let WrongDescription(problems~) = self
  "wrong descriptions of types: \{problems.iter().collect().join("; ")}"
}

///|
/// What the descriptions have registered so far.
priv struct Registry {
  builder : @schema.SchemaContextBuilder
  /// The identity of the key of each described type.
  keys : Map[@nodes.XamlTypeName, Int32]
  problems : Array[String]
  /// How many choices are being registered, each as a case of the one before.
  mut choice_depth : Int32
  /// Whether a choice has itself as a case.
  mut has_endless_choice : Bool
}

///|
/// Add a problem, once for each text.
fn Registry::add_problem(self : Registry, problem : String) -> Unit {
  if !self.problems.contains(problem) {
    self.problems.push(problem)
  }
}

///|
/// The schema context for values of `T`.
fn[T] XamlCodec::schema_context(
  self : XamlCodec[T],
) -> @schema.SchemaContext raise CodecError {
  if self.context.val is Some(context) && self.problem is None {
    return context
  }
  let registry = {
    builder: container_types(),
    keys: Map([]),
    problems: [],
    choice_depth: 0,
    has_endless_choice: false,
  }
  if self.problem is Some(problem) {
    registry.add_problem(problem)
  }
  (self.register)(registry)
  let context = try registry.builder.build() catch {
    Conflicts(conflicts) => {
      for conflict in conflicts {
        registry.add_problem(conflict.message())
      }
      None
    }
  } noraise {
    context => Some(context)
  }
  guard context is Some(context) && registry.problems.is_empty() else {
    raise WrongDescription(
      problems=ReadOnlyArray::from_array(registry.problems),
    )
  }
  self.context.val = Some(context)
  context
}

///|
/// Read the XAML document `text` as a value of type `T`.
///
/// It raises what `parse` raises: `ReaderFailed` when the document is not valid XAML, and `InvalidNode` with the place in `text`
/// when a value cannot be created or the root is of another type. `CodecError` is for a description that cannot work.
pub fn[T : Xaml] from_text(
  text : String,
  settings~ : LoadSettings = LoadSettings::new(),
) -> T raise {
  let codec : XamlCodec[T] = Xaml::xaml_codec()
  let context = codec.schema_context()
  let { root, .. } = parse(text, context, settings~)
  (codec.check)(root) catch {
    error =>
      raise root_error(
        text_reader(text, context, settings),
        @schema.error_message(error),
      )
  }
  (codec.from_xaml)(root)
}

///|
/// Write `value` as a XAML document, as `save` writes it. A value that is in several places is written once, with references
/// to it.
///
/// It raises what `save` raises, and `CodecError` for a description that cannot work.
pub fn[T : Xaml] to_text(
  value : T,
  settings~ : SaveSettings = SaveSettings::new(),
) -> String raise {
  let codec : XamlCodec[T] = Xaml::xaml_codec()
  let context = codec.schema_context()
  save((codec.to_xaml)(value), context, settings~)
}

///|
/// An error about the root, which is the first object of `reader`.
fn root_error(
  reader : @reader.XamlTextReader,
  message : String,
) -> @nodes.XamlWriteError {
  for index = 0; reader.read(); index = index + 1 {
    if reader.node() is Some(StartObject(_) as node) {
      return InvalidNode(
        node~,
        index~,
        message="the root: \{message}",
        span=reader.source_span(),
      )
    }
  }
  missing_root
}

///|
/// The error for `value` where one of the type `needed` is needed.
fn not_a(
  value : @nodes.XamlValue,
  needed : @nodes.XamlTypeName,
) -> @schema.ValueError {
  ValueError("\{describe_value(value)} is not of the type \{needed}")
}

///|
fn describe_value(value : @nodes.XamlValue) -> String {
  match @schema.value_type_name(value) {
    Some(name) => "a value of the type \{name}"
    None => "null"
  }
}