// The lists and maps in members. Their XAML types are never in a document (design F6 of add-xaml-codecs).

///|
/// The items of a list member.
priv struct ListValue {
  items : Array[@nodes.XamlValue]
  add : (@nodes.XamlValue) -> Unit raise
}

///|
/// The entries of a map member.
priv struct MapValue {
  entries : Array[(@nodes.XamlValue, @nodes.XamlValue)]
  add : (@nodes.XamlValue, @nodes.XamlValue) -> Unit raise
}

///|
let list_key : @nodes.ObjectKey[ListValue] = @nodes.ObjectKey::new()

///|
let map_key : @nodes.ObjectKey[MapValue] = @nodes.ObjectKey::new()

///|
let container_namespace : String = "urn:moonrockz:xaml:containers"

///|
let list_type : @nodes.XamlTypeName = @nodes.XamlTypeName::new(
  container_namespace, "List",
)

///|
let map_type : @nodes.XamlTypeName = @nodes.XamlTypeName::new(
  container_namespace, "Map",
)

///|
/// A new builder with the types of the lists and maps.
fn container_types() -> @schema.SchemaContextBuilder {
  let item_type = @schema.type_parameter("T")
  let key_type = @schema.type_parameter("K")
  let list = @schema.XamlTypeDefinition::new(
      list_type.namespace_uri,
      list_type.name,
      type_parameters=["T"],
    )
    .object_key(list_key)
    .collection((target, item) => (list_of(target).add)(item), item_type~)
    .item_enumerator(target => ReadOnlyArray::from_array(list_of(target).items))
  let map = @schema.XamlTypeDefinition::new(
      map_type.namespace_uri,
      map_type.name,
      type_parameters=["K", "T"],
    )
    .object_key(map_key)
    .dictionary(
      (target, key, item) => (map_of(target).add)(key, item),
      key_type~,
      item_type~,
    )
    .entry_enumerator(target => {
      ReadOnlyArray::from_array(map_of(target).entries)
    })
  @schema.SchemaContextBuilder::new().add_type(list).add_type(map)
}

///|
fn list_of(target : @nodes.XamlObject) -> ListValue raise {
  guard list_key.unwrap(target) is Some(list) else {
    raise not_a(Object(target), list_type)
  }
  list
}

///|
fn map_of(target : @nodes.XamlObject) -> MapValue raise {
  guard map_key.unwrap(target) is Some(map) else {
    raise not_a(Object(target), map_type)
  }
  map
}

///|
/// The type of a list with items of the codec `item`.
fn[V] list_type_of(item : XamlCodec[V]) -> @nodes.XamlTypeName {
  { ..list_type, type_arguments: [item.item_type()], }
}

///|
/// The type of a map with keys of the codec `key` and items of the codec `item`.
fn[K, V] map_type_of(
  key : XamlCodec[K],
  item : XamlCodec[V],
) -> @nodes.XamlTypeName {
  { ..map_type, type_arguments: [key.type_name, item.item_type()], }
}

///|
/// The item type for values of the codec. No type has the numbers and null, so optional items are `x:Object`, of which the codec
/// takes those that fit.
fn[T] XamlCodec::item_type(self : XamlCodec[T]) -> @nodes.XamlTypeName {
  if self.nullable {
    @schema.object_type
  } else {
    self.type_name
  }
}

///|
/// The list `items` of the member `name`, to which values with the codec `item` can be added.
fn[V] list_value(
  name : String,
  item : XamlCodec[V],
  items : Array[@nodes.XamlValue],
) -> @nodes.XamlValue {
  fn add(value : @nodes.XamlValue) -> Unit raise {
    (item.check)(value) catch {
      error =>
        raise @schema.ValueError(
          "the list \{name}: \{@schema.error_message(error)}",
        )
    }
    items.push(value)
  }
  Object(list_key.wrap(list_type_of(item), { items, add, }))
}

///|
/// The map `entries` of the member `name`. One entry can be added for each key, as with `Dictionary.Add` of .NET.
fn[K : Eq + Hash, V] map_value(
  name : String,
  key : XamlCodec[K],
  item : XamlCodec[V],
  entries : Array[(@nodes.XamlValue, @nodes.XamlValue)],
) -> @nodes.XamlValue {
  let seen : Map[K, Unit] = Map([])
  fn add(key_value : @nodes.XamlValue, value : @nodes.XamlValue) -> Unit raise {
    try {
      let found = (key.from_xaml)(key_value)
      (item.check)(value)
      if seen.contains(found) {
        let label = key.to_label.map(to_label => to_label(found))
        raise @schema.ValueError(
          "the key \"\{label.unwrap_or("")}\" is there already",
        )
      }
      seen[found] = ()
    } catch {
      error =>
        raise @schema.ValueError(
          "the map \{name}: \{@schema.error_message(error)}",
        )
    }
    entries.push((key_value, value))
  }
  Object(map_key.wrap(map_type_of(key, item), { entries, add, }))
}