// The entry points in the style of System.Xaml `XamlServices` (design D18).

///|
pub using @writer {type LoadSettings, type WriterMode}

///|
/// What `parse` and `load` give.
///
/// On native and wasm, which count references, objects that refer to each other in a circle are freed only when the caller
/// breaks the circle.
pub struct LoadResult {
  /// The root object. It is `Null` when the document stands for null.
  root : @nodes.XamlValue
  /// The name scope of the document, which finds the named objects that no nested name scope has.
  root_name_scope : @writer.LoadedNameScope
}

///|
/// Create the objects of the XAML document `text`, as System.Xaml `XamlServices.Parse` does.
///
/// It raises `ReaderFailed` with the diagnostics when the document is not valid XAML, and `InvalidNode` with the place in
/// `text` when the objects cannot be created. There is no result then, but the constructors and setters that ran before
/// the error keep their effects.
pub fn parse(
  text : String,
  schema_context : @schema.SchemaContext,
  settings~ : LoadSettings = LoadSettings::new(),
) -> LoadResult raise @nodes.XamlWriteError {
  load(text_reader(text, schema_context, settings), schema_context, settings~)
}

///|
fn text_reader(
  text : String,
  schema_context : @schema.SchemaContext,
  settings : LoadSettings,
) -> @reader.XamlTextReader {
  @reader.XamlTextReader::new(
    text,
    schema_context,
    local_scope?=settings.local_scope,
    max_depth=settings.max_depth,
    max_extension_depth=settings.max_extension_depth,
    understood_namespaces=settings.understood_namespaces,
  )
}

///|
/// Create the objects that the nodes of `reader` describe, as System.Xaml `XamlServices.Load` does. The errors are those
/// of `parse`, with the places that the reader gives.
///
/// The depth limits and the understood namespaces of the settings are for the text reader that `parse` makes, so they have
/// no effect here. To copy a graph
/// of objects, give a `XamlObjectReader` with the setting `construction_first`.
pub fn[R : @nodes.XamlReader] load(
  reader : R,
  schema_context : @schema.SchemaContext,
  settings~ : LoadSettings = LoadSettings::new(),
) -> LoadResult raise @nodes.XamlWriteError {
  let writer = @writer.XamlObjectWriter::new(schema_context, settings~)
  @nodes.transfer(reader, writer)
  guard writer.result() is Some(root) &&
    writer.root_name_scope() is Some(root_name_scope) else {
    raise missing_root
  }
  { root, root_name_scope, }
}

///|
/// The error of a stream without a root. `transfer` raises it, so a writer has its result after `transfer`.
let missing_root : @nodes.XamlWriteError = UnbalancedStream(
  reason=MissingRoot,
  node=None,
  index=0,
  span=None,
)

///|
/// The settings of `save`.
pub struct SaveSettings {
  /// Whether a collection or dictionary that only has a getter is written only when its member registers content
  /// visibility.
  require_explicit_content_visibility : Bool
  /// What to do where the text of System.Xaml would be read as something else.
  writer_mode : WriterMode
}

///|
pub fn SaveSettings::new(
  require_explicit_content_visibility~ : Bool = false,
  writer_mode~ : WriterMode = RoundTrip,
) -> SaveSettings {
  { require_explicit_content_visibility, writer_mode, }
}

///|
/// Write `value` and the objects that it reaches as a XAML document, as System.Xaml `XamlServices.Save` does. Elements are
/// on lines of their own, with two spaces for each level and LF line breaks, and there is no XML declaration.
///
/// It raises `ReaderFailed` when a graph cannot be described, such as one with an object that nothing constructs, and
/// `InvalidNode` when a value cannot be written, such as a text with a character that XML does not allow.
pub fn save(
  value : @nodes.XamlValue,
  schema_context : @schema.SchemaContext,
  settings~ : SaveSettings = SaveSettings::new(),
) -> String raise @nodes.XamlWriteError {
  let { require_explicit_content_visibility, writer_mode, } = settings
  let reader = @reader.XamlObjectReader::new(
    value,
    schema_context,
    settings=@reader.ObjectReaderSettings::new(
      require_explicit_content_visibility~,
      // The mode `SystemXaml` writes the members before the construction as attributes, which are read after it.
      construction_first=writer_mode is RoundTrip,
    ),
  )
  let writer = @writer.XamlTextWriter::new(
    schema_context,
    mode=writer_mode,
    indent=true,
  )
  @nodes.transfer(reader, writer)
  guard writer.text() is Some(text) else { raise missing_root }
  text
}