import "../../graphlib/alg/topsort.js";
import { postorder as C } from "../../graphlib/alg/postorder.js";
import { preorder as O } from "../../graphlib/alg/preorder.js";
import "../../graphlib/graph.js";
import { simplify as P } from "../util.js";
import { feasibleTree as T } from "./feasible-tree.js";
import { longestPath as j, slack as A } from "./util.js";
import v from "../../../../../../lodash-es@4.17.22/node_modules/lodash-es/forEach.js";
import b from "../../../../../../lodash-es@4.17.22/node_modules/lodash-es/find.js";
import B from "../../../../../../lodash-es@4.17.22/node_modules/lodash-es/filter.js";
import D from "../../../../../../lodash-es@4.17.22/node_modules/lodash-es/minBy.js";
s.initLowLimValues = m;
s.initCutValues = c;
s.calcCutValue = h;
s.leaveEdge = k;
s.enterEdge = L;
s.exchangeEdges = y;
function s(e) {
  e = P(e), j(e);
  var n = T(e);
  m(n), c(n, e);
  for (var r, a; r = k(n); )
    a = L(n, e, r), y(n, e, r, a);
}
function c(e, n) {
  var r = C(e, e.nodes());
  r = r.slice(0, r.length - 1), v(r, function(a) {
    I(e, n, a);
  });
}
function I(e, n, r) {
  var a = e.node(r), o = a.parent;
  e.edge(r, o).cutvalue = h(e, n, r);
}
function h(e, n, r) {
  var a = e.node(r), o = a.parent, u = !0, i = n.edge(r, o), t = 0;
  return i || (u = !1, i = n.edge(o, r)), t = i.weight, v(n.nodeEdges(r), function(f) {
    var d = f.v === r, l = d ? f.w : f.v;
    if (l !== o) {
      var p = d === u, w = n.edge(f).weight;
      if (t += p ? w : -w, S(e, r, l)) {
        var g = e.edge(r, l).cutvalue;
        t += p ? -g : g;
      }
    }
  }), t;
}
function m(e, n) {
  arguments.length < 2 && (n = e.nodes()[0]), V(e, {}, 1, n);
}
function V(e, n, r, a, o) {
  var u = r, i = e.node(a);
  return n[a] = !0, v(e.neighbors(a), function(t) {
    Object.prototype.hasOwnProperty.call(n, t) || (r = V(e, n, r, t, a));
  }), i.low = u, i.lim = r++, o ? i.parent = o : delete i.parent, r;
}
function k(e) {
  return b(e.edges(), function(n) {
    return e.edge(n).cutvalue < 0;
  });
}
function L(e, n, r) {
  var a = r.v, o = r.w;
  n.hasEdge(a, o) || (a = r.w, o = r.v);
  var u = e.node(a), i = e.node(o), t = u, f = !1;
  u.lim > i.lim && (t = i, f = !0);
  var d = B(n.edges(), function(l) {
    return f === E(e, e.node(l.v), t) && f !== E(e, e.node(l.w), t);
  });
  return D(d, function(l) {
    return A(n, l);
  });
}
function y(e, n, r, a) {
  var o = r.v, u = r.w;
  e.removeEdge(o, u), e.setEdge(a.v, a.w, {}), m(e), c(e, n), R(e, n);
}
function R(e, n) {
  var r = b(e.nodes(), function(o) {
    return !n.node(o).parent;
  }), a = O(e, r);
  a = a.slice(1), v(a, function(o) {
    var u = e.node(o).parent, i = n.edge(o, u), t = !1;
    i || (i = n.edge(u, o), t = !0), n.node(o).rank = n.node(u).rank + (t ? i.minlen : -i.minlen);
  });
}
function S(e, n, r) {
  return e.hasEdge(n, r);
}
function E(e, n, r) {
  return r.low <= n.lim && n.lim <= r.lim;
}
export {
  s as networkSimplex
};
