// What the object writer knows about an open object.

///|
using @syntax {member_text, value_text, type TypeLookup}

///|
/// A node of the stream, which a load error is about.
priv struct Site {
  node : @nodes.XamlNode
  index : Int32
  span : @nodes.SourceSpan?
}

///|
/// Every error of the object writer itself, with the span of the node or, without one, its index.
fn Site::error(self : Site, message : String) -> @nodes.XamlWriteError {
  InvalidNode(node=self.node, index=self.index, message~, span=self.span)
}

///|
/// Where the node is, for an error about several nodes.
fn Site::position(self : Site) -> String {
  match self.span {
    Some(span) => "line \{span.start.line}, column \{span.start.column}"
    None => "node \{self.index}"
  }
}

///|
/// The namespace URIs of the prefixes in scope. The map is immutable, so every object keeps its own.
type Namespaces = @sorted_map.SortedMap[String, String]

///|
let initial_namespaces : Namespaces = @sorted_map.SortedMap([
  ("xml", @schema.xml_namespace),
])

///|
priv struct ObjectFrame {
  /// The type that the stream names. It decides what members and values mean.
  type_ : @schema.XamlType
  start : Site
  namespaces : Namespaces
  /// The index of the scope that has the names of the members and items.
  scope : Int32
  /// The objects of the enclosing elements and extensions, the nearest first.
  parents : @list.List[@nodes.XamlObject]
  /// The object, once it is created. It is never `Null`.
  mut instance : @nodes.XamlValue?
  /// The type of the instance, which can derive from `type_`. Its operations take the instance.
  mut runtime : @schema.XamlType
  /// What the initialization text waits for. Then there is no instance.
  mut late : Fixup?
  /// The name of the object that the text gives later, and where it is.
  mut late_name : (@nodes.XamlValue, Site)?
  /// Whether initialization text gave the instance.
  mut is_from_text : Bool
  /// Whether the parent has had the instance since its creation.
  mut is_assigned : Bool
  /// The member whose getter gave the instance of a get object.
  mut retrieved_from : @schema.XamlMember?
  key : ItemKey
  mut arguments : ConstructorArguments?
  /// The text of `x:FactoryMethod` and where it is.
  mut factory_method : (String, Site)?
  mut open_member : MemberFrame?
  /// The members that `x:Name`, `x:Uid` and `xml:lang` stand for and that the object already has.
  aliased : Array[@nodes.XamlMemberName]
  /// The registered name with the index of its scope.
  mut name : (Int32, String)?
  /// Whether the object is on the stack.
  mut is_open : Bool
  /// Whether the object is off the stack and has ended.
  mut is_complete : Bool
  /// How many references and unfinished objects must come before the end.
  mut pending : Int32
  /// The objects that wait for this one.
  waiters : Array[ObjectFrame]
  /// The adds to this collection that wait, in document order.
  adds : Array[PendingAdd]
  /// Where the value of this extension goes, when it comes after the end node, and the services for it.
  mut place : (Place, @schema.ServiceContext)?
  /// How many references there were before the object, so that the later ones are in it.
  first_reference : Int32
  /// The position of this collection in `Queues::unhashed`.
  mut queue_index : Int32
  /// The node of the end in the order of the last ends.
  mut node : Int32
}

///|
/// The value of `x:Key`, which can be `Null`. The item has it, and the add that waits for it.
priv struct ItemKey {
  mut value : @nodes.XamlValue?
  mut is_pending : Bool
}

///|
fn ObjectFrame::new(
  type_ : @schema.XamlType,
  start : Site,
  namespaces : Namespaces,
  scope : Int32,
  parents : @list.List[@nodes.XamlObject],
  first_reference : Int32,
) -> ObjectFrame {
  {
    type_,
    start,
    namespaces,
    scope,
    parents,
    instance: None,
    runtime: type_,
    late: None,
    late_name: None,
    is_from_text: false,
    is_assigned: false,
    retrieved_from: None,
    key: { value: None, is_pending: false, },
    arguments: None,
    factory_method: None,
    open_member: None,
    aliased: [],
    name: None,
    is_open: true,
    is_complete: false,
    pending: 0,
    waiters: [],
    adds: [],
    place: None,
    first_reference,
    queue_index: 0,
    node: 0,
  }
}

///|
/// The member that the start of `definition` sets: the member that `x:Name`, `x:Uid` or `xml:lang` stands for on
/// this type, and else `definition`. The directive and its member are one member of the object (System.Xaml
/// `XamlObjectWriter.Logic_ApplyPropertyValue`).
fn ObjectFrame::start_aliased(
  self : ObjectFrame,
  definition : @schema.XamlMember,
  site : Site,
) -> @schema.XamlMember raise @nodes.XamlWriteError {
  let name = definition.member_name()
  for alias_ in [@schema.AliasedDirective::Name, Uid, Lang] {
    guard self.type_.aliased_member(alias_) is Some(target) else { continue }
    let target_name = target.member_name()
    if name != alias_.member_name() && name != target_name {
      continue
    }
    if self.aliased.contains(target_name) {
      raise site.error(
        "duplicate member \{member_text(target_name)} of \{self.type_.name}",
      )
    }
    self.aliased.push(target_name)
    return target
  }
  definition
}

///|
/// Whether the member `name` of the stream, which sets `target`, names the object.
fn ObjectFrame::naming(
  self : ObjectFrame,
  name : @nodes.XamlMemberName,
  target : @schema.XamlMember,
) -> Naming {
  if name == @schema.AliasedDirective::Name.member_name() {
    Text
  } else if self.type_.aliased_member(Name) is Some(alias_) &&
    alias_.member_name() == target.member_name() {
    Converted
  } else {
    No
  }
}

///|
/// The arguments of the constructor or factory method.
priv enum ConstructorArguments {
  /// The values of `x:Arguments`, which select a constructor by their types.
  Bound(Array[@nodes.XamlValue], Site)
  /// Positional parameters, converted for the constructor that their count selects.
  Positional(@schema.XamlConstructor, Array[@nodes.XamlValue], Site)
}

///|
priv struct MemberFrame {
  role : MemberRole
  site : Site
  naming : Naming
  /// The collection with earlier adds of the same object that are queued.
  queue : ObjectFrame?
  /// The values of the member that wait for its end. An object goes to a property at its own end.
  values : Array[MemberValue]
}

///|
/// Whether a member names the object, and with which value.
priv enum Naming {
  No
  /// `x:Name`, with the value of the stream.
  Text
  /// The `x:Name` alias, with the value that the member receives.
  Converted
}

///|
priv struct MemberValue {
  value : @nodes.XamlValue
  site : Site
  /// Whether a value node gives it, so that a converter can take it. Completed objects and the results of
  /// markup extensions are not converted.
  is_raw : Bool
}

///|
fn values_of(values : Array[MemberValue]) -> Array[@nodes.XamlValue] {
  values.map(entry => entry.value)
}

///|
/// What a member does with its values.
priv enum MemberRole {
  /// Sets a property or an attached property. A directive that has no use here is one too, and its value is dropped
  /// in the end (System.Xaml `ClrObjectRuntime.SetValue`).
  Property(@schema.XamlMember)
  /// Gives its nodes, with the span of each, to the adder of an event.
  Event(@schema.XamlMember, Array[(@nodes.XamlNode, @nodes.SourceSpan?)])
  /// Adds its values to the object.
  Items
  Key
  Arguments
  PositionalParameters
  FactoryMethod
  Initialization
  /// Names the object, which has no `x:Name` alias.
  Name
  /// Gives the base URI of the document.
  Base
  /// Names the type of the root. An object in it is skipped, because it is no string.
  Class
}

///|
fn member_role(definition : @schema.XamlMember) -> MemberRole {
  if definition.is_event() {
    return Event(definition, [])
  }
  guard definition.member_name() is Directive(namespace_uri~, name~) else {
    return Property(definition)
  }
  if namespace_uri != @nodes.xaml_language_namespace {
    return if definition.member_name() == base_directive {
      Base
    } else {
      Property(definition)
    }
  }
  match name {
    "_Items" => Items
    "Key" => Key
    "Arguments" => Arguments
    "_PositionalParameters" => PositionalParameters
    "FactoryMethod" => FactoryMethod
    "_Initialization" => Initialization
    "Name" => Name
    "Class" => Class
    _ => Property(definition)
  }
}

///|
/// Whether `name` is a directive that selects a constructor, so that it cannot come after the object is
/// created (System.Xaml `XamlObjectWriter.IsTextConstructionDirective`).
fn selects_constructor(name : @nodes.XamlMemberName) -> Bool {
  name != @syntax.initialization_directive &&
  name != base_directive &&
  @syntax.is_construction_directive(name)
}

///|
let base_directive : @nodes.XamlMemberName = Directive(
  namespace_uri=@schema.xml_namespace,
  name="base",
)

///|
/// Whether the start of the member `name` creates an object of type `type_`. WPF's loader does not pass
/// `xml:space` to the object writer, because it would create the object (`WpfXamlLoader.cs`).
fn creates_object(
  name : @nodes.XamlMemberName,
  type_ : @schema.XamlType,
) -> Bool {
  guard name is Directive(namespace_uri~, name=local_name) else { return true }
  let comes_before = @syntax.is_construction_directive(name) ||
    name == @syntax.key_directive ||
    (namespace_uri == @schema.xml_namespace && local_name == "space") ||
    (
      namespace_uri == @nodes.xaml_language_namespace &&
      local_name == @schema.directive_uid &&
      type_.aliased_member(Uid) is None
    )
  !comes_before
}

///|
fn unknown_type(
  name : @nodes.XamlTypeName,
  error : @schema.TypeResolutionError,
) -> String {
  match error {
    UnknownType(unknown) if unknown == name => "unknown type \{name}"
    _ => "unknown type \{name}: \{error.message()}"
  }
}

///|
fn unknown_member(name : @nodes.XamlMemberName) -> String {
  match name {
    Member(owner~, name~) => "unknown member \{name} of \{owner}"
    Attached(owner~, name~) => "unknown attached member \{name} of \{owner}"
    Directive(_) | UnknownDirective(_) =>
      "unknown directive \{member_text(name)}"
  }
}