///|
/// Sequence elements. A frame owns its sections and a section owns its events.
/// Message endpoints, notes and activations name participants by reference.
#derive(Eq, Debug)
pub(all) enum SequenceElement {
  Diagram(String?)
  Box(@sequence.BoxGroup)
  Participant(@sequence.Participant)
  Event(@sequence.Event)
  Section(@sequence.Section)
}

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

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

///|
pub fn SequenceElement::kind_name(self : SequenceElement) -> String {
  match self {
    Diagram(_) => "diagram"
    Box(_) => "box"
    Participant(_) => "participant"
    Event(Message(_)) => "message"
    Event(Note(_)) => "note"
    Event(Activate(_)) => "activate"
    Event(Deactivate(_)) => "deactivate"
    Event(Create(_)) => "create"
    Event(Destroy(_)) => "destroy"
    Event(Frame(_)) => "frame"
    Event(Autonumber(_)) => "autonumber"
    Section(_) => "section"
  }
}

///|
pub fn SequenceElement::id(self : SequenceElement) -> String? {
  match self {
    Box(v) => Some(v.id)
    Participant(v) => Some(v.id)
    _ => None
  }
}

///|
priv enum SequenceWork {
  Events(ReadOnlyArray[@sequence.Event], Int32)
  Sections(ReadOnlyArray[@sequence.Section], Int32)
}

///|
/// Index a sequence. Root children are boxes (at the first participant that
/// names them), participants outside a box, then events in model order. A box
/// owns its participants, a frame its sections and a section its events.
pub fn Tree::sequence(
  view : @sequence.Sequence,
  limits~ : IndexLimits = IndexLimits::new(),
  revision~ : Int32 = 0,
) -> Result[Tree, String] {
  let b = Builder::new(Sequence(Diagram(view.title)), limits)
  let boxes : Map[String, Int32] = Map([])
  for participant in view.participants {
    let parent = match participant.group {
      Some(group) =>
        match boxes.get(group.id) {
          Some(index) => index
          None => {
            let index = b.add(Sequence(Box(group)))
            boxes[group.id] = index
            index
          }
        }
      None => 0
    }
    b.add(
      Sequence(Participant(participant)),
      parent~,
      slot=b.slot("participant"),
    )
    |> ignore
  }
  // Each work item holds a remaining slice; slices keep pre-order without recursion.
  let stack : Array[(SequenceWork, Int32)] = [(Events(view.events, 0), 0)]
  while stack.pop() is Some((work, position)) {
    if !b.charge(1) {
      break
    }
    match work {
      Events(events, parent) =>
        if position < events.length() {
          stack.push((work, position + 1))
          let event = events[position]
          let index = b.add(Sequence(Event(event)), parent~, slot=position)
          if event is Frame(frame) && index >= 0 {
            stack.push((Sections(frame.sections, index), 0))
          }
        }
      Sections(sections, parent) =>
        if position < sections.length() {
          stack.push((work, position + 1))
          let section = sections[position]
          let index = b.add(Sequence(Section(section)), parent~, slot=position)
          if index >= 0 {
            stack.push((Events(section.events, index), 0))
          }
        }
    }
  }
  b.finish(revision)
}