import { forEach as o, find as _, map as H } from "../../../min-dash/dist/index.esm.mjs";
import tn from "./BpmnTreeWalker.mjs";
import { is as u } from "../util/ModelUtil.mjs";
function y(e, r, t) {
  var o$1, a, s, u2, v, l = [];
  function i(n, f) {
    var d = {
      root: function(p, c) {
        return o$1.add(p, c);
      },
      element: function(p, c, I) {
        return o$1.add(p, c, I);
      },
      error: function(p, c) {
        l.push({ message: p, context: c });
      }
    }, R = new tn(d, s);
    f = f || n.diagrams && n.diagrams[0];
    var h = C(n, f);
    if (!h)
      throw new Error(s("no diagram to display"));
    o(h, function(p) {
      R.handleDefinitions(n, p);
    });
    var w = f.plane.bpmnElement.id;
    u2.setRootElement(
      u2.findRoot(w + "_plane") || u2.findRoot(w)
    );
  }
  return new Promise(function(n, f) {
    try {
      return o$1 = e.get("bpmnImporter"), a = e.get("eventBus"), s = e.get("translate"), u2 = e.get("canvas"), a.fire("import.render.start", { definitions: r }), i(r, t), a.fire("import.render.complete", {
        error: v,
        warnings: l
      }), n({ warnings: l });
    } catch (d) {
      return d.warnings = l, f(d);
    }
  });
}
function C(e, r) {
  if (r) {
    var t = r.plane.bpmnElement, o$1 = t;
    !u(t, "bpmn:Process") && !u(t, "bpmn:Collaboration") && (o$1 = P(t));
    var a;
    u(o$1, "bpmn:Collaboration") ? a = o$1 : a = _(e.rootElements, function(i) {
      if (u(i, "bpmn:Collaboration"))
        return _(i.participants, function(n) {
          return n.processRef === o$1;
        });
    });
    var s = [o$1];
    a && (s = H(a.participants, function(i) {
      return i.processRef;
    }), s.push(a));
    var u$1 = g(s), v = [r], l = [t];
    return o(e.diagrams, function(i) {
      var n = i.plane.bpmnElement;
      u$1.indexOf(n) !== -1 && l.indexOf(n) === -1 && (v.push(i), l.push(n));
    }), v;
  }
}
function g(e) {
  var r = [];
  return o(e, function(t) {
    t && (r.push(t), r = r.concat(g(t.flowElements)));
  }), r;
}
function P(e) {
  for (var r = e; r; ) {
    if (u(r, "bpmn:Process"))
      return r;
    r = r.$parent;
  }
}
export {
  y as importBpmnDiagram
};
