///|
/// Swimlane elements. Connections are references, not children.
#derive(Eq, Debug)
pub(all) enum SwimlaneElement {
  Diagram(String)
  Lane(@swimlane.Lane)
  Group(@swimlane.Group)
  Node(@swimlane.Node)
  Connection(@swimlane.Connection)
}

///|
pub extend SwimlaneElement with Eq::{equal, not_equal}

///|
pub extend SwimlaneElement with @debug.Debug::{to_repr}

///|
pub fn SwimlaneElement::kind_name(self : SwimlaneElement) -> String {
  match self {
    Diagram(_) => "diagram"
    Lane(_) => "lane"
    Group(_) => "group"
    Node(_) => "node"
    Connection(_) => "connection"
  }
}

///|
pub fn SwimlaneElement::id(self : SwimlaneElement) -> String? {
  match self {
    Diagram(id) => Some(id)
    Lane(v) => Some(v.id)
    Group(v) => Some(v.id)
    Node(v) => Some(v.id)
    Connection(v) => Some(v.id)
  }
}

///|
/// Index a swimlane. Root children are lanes, groups, nodes and connections in
/// field order. A group belongs to its parent group, else its lane; a node to
/// its innermost group, else its lane. Connections stay references.
pub fn Tree::swimlane(
  view : @swimlane.Swimlane,
  limits~ : IndexLimits = IndexLimits::new(),
  revision~ : Int32 = 0,
) -> Result[Tree, String] {
  let b = Builder::new(Swimlane(Diagram(view.id)), limits)
  for lane in view.lanes {
    b.register(
      "lane",
      lane.id,
      b.add(Swimlane(Lane(lane)), slot=b.slot("lane")),
    )
  }
  let groups = view.groups.map(group => {
    let index = b.add(Swimlane(Group(group)), slot=b.slot("group"))
    b.register("group", group.id, index)
    index
  })
  let nodes = view.nodes.map(node => {
    b.add(Swimlane(Node(node)), slot=b.slot("node"))
  })
  for edge in view.connections {
    b.add(Swimlane(Connection(edge)), slot=b.slot("connection")) |> ignore
  }
  fn place(index : Int32, group : String?, lane : String?) -> Unit {
    match group {
      Some(id) => b.own(index, b.container("group", id))
      None => if lane is Some(id) { b.own(index, b.container("lane", id)) }
    }
  }
  for i, group in view.groups {
    place(groups[i], group.parent, group.lane)
  }
  for i, node in view.nodes {
    place(nodes[i], node.groups.last(), node.lane)
  }
  b.finish(revision)
}