///|
fn encoded_path_segment(value : String) -> String {
  let output = StringBuilder(capacity=value.length())
  for character in value.iter() {
    if (character >= 'a' && character <= 'z') ||
      (character >= 'A' && character <= 'Z') ||
      (character >= '0' && character <= '9') ||
      character == '_' ||
      character == '-' {
      output.write_char(character)
    } else {
      output.write_char('_')
      output.write_string(character.to_int().to_string(radix=16))
      output.write_char('_')
    }
  }
  output.to_string()
}

///|
priv struct BindingScope {
  direct : Map[String, @renderer.PageEvent[Cmd]]
  children : Map[Int32, Array[NodeBinding]]
}

///|
/// Index only this authoring node. Its retained children own their bindings.
fn BindingScope::new(bindings : Array[NodeBinding]) -> BindingScope {
  let direct = Map([])
  let children = Map([])
  for binding in bindings {
    match binding {
      DirectBinding(event) => direct[event.key()] = event
      NestedBindings(id, nested) => children[id] = nested
    }
  }
  { direct, children, }
}

///|
fn materialized_event_key(
  binding : @renderer.PageEvent[Cmd],
  path : String,
) -> String {
  let parts = binding.key().split("|").collect()
  if parts.length() > 1 && parts[1] != "" {
    parts[1].to_owned()
  } else {
    "v/" + path + "/" + binding.kind().host_name()
  }
}

///|
priv struct CachedMaterialization {
  raw : @ui.Node
  tree : @ui.Node
  first : Int32
  end : Int32
}

///|
priv struct Materialization {
  nodes : Map[(Int32, String), CachedMaterialization]
  // Entries belong to this page generation and are dropped on rollback or unload.
  registrations : Array[(String, @renderer.PageEvent[Cmd])]
}

///|
fn Materialization::new() -> Materialization {
  { nodes: Map([]), registrations: [], }
}

///|
priv struct Projection {
  previous : Materialization
  next : Materialization
  events : @renderer.Events[GraphMessage]
}

///|
fn Projection::register(
  self : Projection,
  key : String,
  binding : @renderer.PageEvent[Cmd],
) -> Unit {
  self.next.registrations.push((key, binding))
  ignore(
    self.events.custom(key, binding.kind(), payload => {
      match binding.decode(payload) {
        Ok(command) => Ok(GraphCommand(command))
        Err(error) => Err(error)
      }
    }),
  )
}

///|
fn materialize_retained(
  node : @ui.Node,
  identity : Int32,
  child : @ui.Node,
  path : String,
  bindings : Array[NodeBinding],
  projection : Projection,
) -> @ui.Node {
  let cache_key = (identity, path)
  let first = projection.next.registrations.length()
  let tree = if projection.previous.nodes.get(cache_key) is Some(hit) &&
    physical_equal(node, hit.raw) {
    for index in hit.first.. @ui.Node {
  match node {
    @ui.Text(_) | @ui.Empty => node
    @ui.Retained(identity, child) =>
      match scope.children.get(identity) {
        Some(bindings) =>
          materialize_retained(
            node, identity, child, path, bindings, projection,
          )
        None => node
      }
    @ui.Fragment(children) => {
      let output : Array[@ui.Node] = []
      for index = 0; index < children.length(); index = index + 1 {
        output.push(
          materialize_node(
            children[index],
            path + "/i:" + index.to_string(),
            scope,
            projection,
          ),
        )
      }
      @ui.fragment(output)
    }
    @ui.KeyedFragment(children) => {
      let output : Array[@ui.KeyedNode] = []
      for child in children {
        output.push(
          @ui.keyed(
            child.key(),
            materialize_node(
              child.node(),
              path + "/k:" + encoded_path_segment(child.key()),
              scope,
              projection,
            ),
          ),
        )
      }
      @ui.keyed_fragment(output)
    }
    @ui.Element(tag, attrs, children) => {
      let next_attrs = attrs.map(attr => {
        if attr.name.has_prefix("on_") && attr.value.has_prefix("$minimoon:") {
          let binding = scope.direct
            .get(attr.value)
            .unwrap_or_else(fn() {
              abort("missing event binding: " + attr.value)
            })
          let key = materialized_event_key(binding, path)
          projection.register(key, binding)
          @ui.attr(attr.name, key)
        } else {
          attr
        }
      })
      let next_children : Array[@ui.Node] = []
      for index = 0; index < children.length(); index = index + 1 {
        next_children.push(
          materialize_node(
            children[index],
            path + "/i:" + index.to_string(),
            scope,
            projection,
          ),
        )
      }
      @ui.element(tag, attrs=next_attrs, children=next_children)
    }
  }
}

///|
fn materialize(
  node : Node,
  events : @renderer.Events[GraphMessage],
  previous : Materialization,
  next : Materialization,
) -> @ui.Node {
  if node.bindings.is_empty() {
    return node.raw
  }
  guard node.raw is @ui.Retained(identity, child) else {
    abort("authoring node must retain its binding scope")
  }
  materialize_retained(node.raw, identity, child, "root", node.bindings, {
    previous,
    next,
    events,
  })
}