///|
fn unsupported(
  findings : Array[@diagrams.Diagnostic],
  tree : @observation.Tree,
  ordinal : Int32,
  property : String,
) -> Unit {
  let element = tree.element(ordinal).unwrap()
  findings.push(
    @diagrams.Diagnostic::warning(
      "projection/unsupported-override",
      "A \{element.family()} \{element.kind_name()} cannot apply the override '\{property}' (\{visual_key(ordinal, Body)})",
    ),
  )
}

///|
/// Report each layout property of `m` that the element cannot apply.
fn reject(
  findings : Array[@diagrams.Diagnostic],
  tree : @observation.Tree,
  ordinal : Int32,
  m : Merged,
  label~ : Bool = false,
  shape~ : Bool = false,
  collapsed~ : Bool = false,
  hidden~ : Bool = false,
) -> Unit {
  if !label && m.label is Some(_) {
    unsupported(findings, tree, ordinal, "label")
  }
  if !shape && m.shape is Some(_) {
    unsupported(findings, tree, ordinal, "shape")
  }
  if !collapsed && m.collapsed is Some(_) {
    unsupported(findings, tree, ordinal, "collapsed")
  }
  if !hidden && m.hidden is Some(_) {
    unsupported(findings, tree, ordinal, "hidden")
  }
}

///|
fn changes_layout(m : Merged) -> Bool {
  m.label is Some(_) ||
  m.shape is Some(_) ||
  m.collapsed is Some(_) ||
  m.hidden is Some(_)
}

///|
/// The diagram that layout uses. Elements keep their model positions, so
/// geometry and routes are recomputed from the changed inputs only.
fn layout_input(
  model : Model,
  merged : Map[Int32, Merged],
  findings : Array[@diagrams.Diagnostic],
) -> @render.Diagram {
  if !merged.values().any(changes_layout) {
    return model.diagram
  }
  let tree = model.tree
  let entries = merged.to_array().filter(e => changes_layout(e.1))
  entries.sort_by_key(e => e.0)
  match model.diagram {
    Flowchart(view) =>
      Flowchart(flowchart_layout(view, tree, entries, findings))
    Swimlane(view) => Swimlane(swimlane_layout(view, tree, entries, findings))
    State(view) => State(state_layout(view, tree, entries, findings))
    Sequence(view) => Sequence(sequence_layout(view, tree, entries, findings))
    Bpmn(view) => Bpmn(bpmn_layout(view, tree, entries, findings))
    Architecture(view) =>
      Architecture(architecture_layout(view, tree, entries, findings))
    Regex(_) | Ebnf(_) | DataTree(_) => {
      for entry in entries {
        reject(findings, tree, entry.0, entry.1)
      }
      model.diagram
    }
  }
}

///|
fn flowchart_layout(
  view : @flowchart.Flowchart,
  tree : @observation.Tree,
  entries : Array[(Int32, Merged)],
  findings : Array[@diagrams.Diagnostic],
) -> @flowchart.Flowchart {
  let nodes = view.nodes.iter().to_array()
  let groups = view.groups.iter().to_array()
  let lanes = view.lanes.iter().to_array()
  let connections = view.connections.iter().to_array()
  let notes = view.notes.iter().to_array()
  let hidden_nodes : Map[String, Bool] = Map([])
  let hidden_connections : Map[Int32, Bool] = Map([])
  let hidden_notes : Map[Int32, Bool] = Map([])
  for entry in entries {
    let (i, m) = entry
    let slot = tree.slot(i)
    match tree.element(i) {
      Some(Flowchart(Node(node))) => {
        reject(findings, tree, i, m, label=true, shape=true, hidden=true)
        let mut next = nodes[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if m.shape is Some(shape) {
          next = next.with_shape(shape)
        }
        nodes[slot] = next
        if m.hidden == Some(true) {
          if node.regions.is_empty() {
            hidden_nodes[node.id] = true
          } else {
            unsupported(findings, tree, i, "hidden")
          }
        }
      }
      Some(Flowchart(Group(_))) => {
        reject(findings, tree, i, m, label=true, collapsed=true)
        let mut next = groups[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if m.collapsed is Some(collapsed) {
          next = next.with_expanded(!collapsed)
        }
        groups[slot] = next
      }
      Some(Flowchart(Lane(_))) => {
        reject(findings, tree, i, m, label=true, collapsed=true)
        let mut next = lanes[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if m.collapsed is Some(collapsed) {
          next = next.with_expanded(!collapsed)
        }
        lanes[slot] = next
      }
      Some(Flowchart(Connection(_))) => {
        reject(findings, tree, i, m, label=true, hidden=true)
        if m.label is Some(label) {
          connections[slot] = connections[slot].with_label(label)
        }
        if m.hidden == Some(true) {
          hidden_connections[slot] = true
        }
      }
      Some(Flowchart(Note(_))) => {
        reject(findings, tree, i, m, label=true, hidden=true)
        if m.label is Some(label) {
          notes[slot] = notes[slot].with_text(label)
        }
        if m.hidden == Some(true) {
          hidden_notes[slot] = true
        }
      }
      _ => reject(findings, tree, i, m)
    }
  }
  // Hiding is rendering-only: dependent connections and notes leave the
  // layout input with the node, but the model and its index are unchanged.
  let kept_connections = []
  for j, edge in connections {
    if !hidden_connections.contains(j) &&
      !hidden_nodes.contains(edge.source) &&
      !hidden_nodes.contains(edge.target) {
      kept_connections.push(edge)
    }
  }
  let kept_notes = []
  for j, note in notes {
    if !hidden_notes.contains(j) &&
      !note.targets.iter().any(t => hidden_nodes.contains(t)) {
      kept_notes.push(note)
    }
  }
  view
  .with_nodes(nodes.filter(n => !hidden_nodes.contains(n.id)))
  .with_groups(groups)
  .with_lanes(lanes)
  .with_connections(kept_connections)
  .with_notes(kept_notes)
}

///|
fn swimlane_layout(
  view : @swimlane.Swimlane,
  tree : @observation.Tree,
  entries : Array[(Int32, Merged)],
  findings : Array[@diagrams.Diagnostic],
) -> @swimlane.Swimlane {
  let nodes = view.nodes.iter().to_array()
  let groups = view.groups.iter().to_array()
  let lanes = view.lanes.iter().to_array()
  let connections = view.connections.iter().to_array()
  let hidden_nodes : Map[String, Bool] = Map([])
  let hidden_connections : Map[Int32, Bool] = Map([])
  for entry in entries {
    let (i, m) = entry
    let slot = tree.slot(i)
    match tree.element(i) {
      Some(Swimlane(Node(node))) => {
        reject(findings, tree, i, m, label=true, shape=true, hidden=true)
        let mut next = nodes[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if m.shape is Some(shape) {
          next = next.with_shape(shape)
        }
        nodes[slot] = next
        if m.hidden == Some(true) {
          hidden_nodes[node.id] = true
        }
      }
      Some(Swimlane(Group(_))) => {
        reject(findings, tree, i, m, label=true, collapsed=true)
        let mut next = groups[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if m.collapsed is Some(collapsed) {
          next = next.with_expanded(!collapsed)
        }
        groups[slot] = next
      }
      Some(Swimlane(Lane(_))) => {
        reject(findings, tree, i, m, label=true, collapsed=true)
        let mut next = lanes[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if m.collapsed is Some(collapsed) {
          next = next.with_expanded(!collapsed)
        }
        lanes[slot] = next
      }
      Some(Swimlane(Connection(_))) => {
        reject(findings, tree, i, m, label=true, hidden=true)
        if m.label is Some(label) {
          connections[slot] = connections[slot].with_label(label)
        }
        if m.hidden == Some(true) {
          hidden_connections[slot] = true
        }
      }
      _ => reject(findings, tree, i, m)
    }
  }
  let kept = []
  for j, edge in connections {
    if !hidden_connections.contains(j) &&
      !hidden_nodes.contains(edge.source) &&
      !hidden_nodes.contains(edge.target) {
      kept.push(edge)
    }
  }
  view
  .with_nodes(nodes.filter(n => !hidden_nodes.contains(n.id)))
  .with_groups(groups)
  .with_lanes(lanes)
  .with_connections(kept)
}

///|
fn state_layout(
  view : @state.StateDiagram,
  tree : @observation.Tree,
  entries : Array[(Int32, Merged)],
  findings : Array[@diagrams.Diagnostic],
) -> @state.StateDiagram {
  let states = view.states.iter().to_array()
  let transitions = view.transitions.iter().to_array()
  let notes = view.notes.iter().to_array()
  for entry in entries {
    let (i, m) = entry
    let slot = tree.slot(i)
    match tree.element(i) {
      Some(State(State(state))) => {
        let composite = state.role == Composite
        reject(findings, tree, i, m, label=true, collapsed=composite)
        let mut next = states[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if composite && m.collapsed is Some(collapsed) {
          next = next.with_expanded(!collapsed)
        }
        states[slot] = next
      }
      Some(State(Transition(_))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          transitions[slot] = transitions[slot].with_label(label)
        }
      }
      Some(State(Note(_))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          notes[slot] = notes[slot].with_text(label)
        }
      }
      _ => reject(findings, tree, i, m)
    }
  }
  view.with_states(states).with_transitions(transitions).with_notes(notes)
}

///|
fn sequence_layout(
  view : @sequence.Sequence,
  tree : @observation.Tree,
  entries : Array[(Int32, Merged)],
  findings : Array[@diagrams.Diagnostic],
) -> @sequence.Sequence {
  let participants = view.participants.iter().to_array()
  let labels : Map[Int32, String] = Map([])
  for entry in entries {
    let (i, m) = entry
    match tree.element(i) {
      Some(Sequence(Participant(_))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          participants[tree.slot(i)] = participants[tree.slot(i)].with_label(
            label,
          )
        }
      }
      Some(Sequence(Event(Message(_) | Note(_)))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          labels[i] = label
        }
      }
      _ => reject(findings, tree, i, m)
    }
  }
  if labels.is_empty() {
    return view.with_participants(participants)
  }
  // Rebuild changed events bottom-up so nested frames need no recursion.
  let events : Map[Int32, @sequence.Event] = Map([])
  let sections : Map[Int32, @sequence.Section] = Map([])
  fn rebuilt(children : ReadOnlyArray[Int32]) -> Array[@sequence.Event]? {
    if !children.iter().any(c => events.contains(c)) {
      return None
    }
    Some(
      children
      .iter()
      .map(c => {
        match events.get(c) {
          Some(event) => event
          None =>
            match tree.element(c) {
              Some(Sequence(Event(event))) => event
              _ => abort("sequence section child is not an event")
            }
        }
      })
      .to_array(),
    )
  }
  let order = pre_order(tree)
  for k = order.length() - 1; k >= 0; k = k - 1 {
    let i = order[k]
    match tree.element(i) {
      Some(Sequence(Event(Message(message)))) =>
        if labels.get(i) is Some(label) {
          events[i] = Message(message.with_label(label))
        }
      Some(Sequence(Event(Note(note)))) =>
        if labels.get(i) is Some(label) {
          events[i] = Note(note.with_text(label))
        }
      Some(Sequence(Section(section))) =>
        if rebuilt(tree.children(i)) is Some(items) {
          sections[i] = @sequence.Section::new(
            items,
            label?=section.label,
            role=section.role,
          )
        }
      Some(Sequence(Event(Frame(frame)))) => {
        let children = tree.children(i)
        if children.iter().any(c => sections.contains(c)) {
          let items = children
            .iter()
            .map(c => {
              match sections.get(c) {
                Some(section) => section
                None =>
                  match tree.element(c) {
                    Some(Sequence(Section(section))) => section
                    _ => abort("sequence frame child is not a section")
                  }
              }
            })
            .to_array()
          events[i] = Frame(
            @sequence.Frame::new(
              frame.kind,
              items[0],
              rest=items[1:],
              colour?=frame.colour,
            ),
          )
        }
      }
      _ => ()
    }
  }
  let top = tree
    .children(0)
    .iter()
    .filter(c => tree.element(c) is Some(Sequence(Event(_))))
    .to_array()
  match rebuilt(ReadOnlyArray::from_array(top)) {
    Some(items) => view.with_participants(participants).with_events(items)
    None => view.with_participants(participants)
  }
}

///|
fn bpmn_layout(
  view : @bpmn.Bpmn,
  tree : @observation.Tree,
  entries : Array[(Int32, Merged)],
  findings : Array[@diagrams.Diagnostic],
) -> @bpmn.Bpmn {
  let nodes = view.nodes.iter().to_array()
  let flows = view.flows.iter().to_array()
  for entry in entries {
    let (i, m) = entry
    let slot = tree.slot(i)
    match tree.element(i) {
      Some(Bpmn(Node(node))) => {
        let container = node.expanded is Some(_)
        reject(findings, tree, i, m, label=true, collapsed=container)
        let mut next = nodes[slot]
        if m.label is Some(label) {
          next = next.with_label(label)
        }
        if container && m.collapsed is Some(collapsed) {
          next = next.with_expanded(Some(!collapsed))
        }
        nodes[slot] = next
      }
      Some(Bpmn(Flow(_))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          flows[slot] = flows[slot].with_label(label)
        }
      }
      _ => reject(findings, tree, i, m)
    }
  }
  view.with_nodes(nodes).with_flows(flows)
}

///|
fn architecture_layout(
  view : @architecture.Architecture,
  tree : @observation.Tree,
  entries : Array[(Int32, Merged)],
  findings : Array[@diagrams.Diagnostic],
) -> @architecture.Architecture {
  let services = view.services.iter().to_array()
  let groups = view.groups.iter().to_array()
  let connections = view.connections.iter().to_array()
  for entry in entries {
    let (i, m) = entry
    let slot = tree.slot(i)
    match tree.element(i) {
      Some(Architecture(Service(_))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          services[slot] = services[slot].with_label(label)
        }
      }
      Some(Architecture(Group(_))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          groups[slot] = groups[slot].with_label(label)
        }
      }
      Some(Architecture(Connection(_))) => {
        reject(findings, tree, i, m, label=true)
        if m.label is Some(label) {
          connections[slot] = connections[slot].with_label(Some(label))
        }
      }
      _ => reject(findings, tree, i, m)
    }
  }
  view.with_services(services).with_groups(groups).with_connections(connections)
}