'use strict';

var graph = require('../graphlib/graph.js');
var forEach = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/forEach.js');
var min = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/min.js');
var map = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/map.js');
var isUndefined = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/isUndefined.js');
var has = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/has.js');
var uniqueId = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/uniqueId.js');
var range = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/range.js');
var max = require('../../../../../lodash-es@4.17.23/node_modules/lodash-es/max.js');

/*
 * Adds a dummy node to the graph and return v.
 */
function addDummyNode(g, type, attrs, name) {
  var v;
  do {
    v = uniqueId.default(name);
  } while (g.hasNode(v));

  attrs.dummy = type;
  g.setNode(v, attrs);
  return v;
}

/*
 * Returns a new graph with only simple edges. Handles aggregation of data
 * associated with multi-edges.
 */
function simplify(g) {
  var simplified = new graph.Graph().setGraph(g.graph());
  forEach.default(g.nodes(), function (v) {
    simplified.setNode(v, g.node(v));
  });
  forEach.default(g.edges(), function (e) {
    var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 };
    var label = g.edge(e);
    simplified.setEdge(e.v, e.w, {
      weight: simpleLabel.weight + label.weight,
      minlen: Math.max(simpleLabel.minlen, label.minlen),
    });
  });
  return simplified;
}

function asNonCompoundGraph(g) {
  var simplified = new graph.Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph());
  forEach.default(g.nodes(), function (v) {
    if (!g.children(v).length) {
      simplified.setNode(v, g.node(v));
    }
  });
  forEach.default(g.edges(), function (e) {
    simplified.setEdge(e, g.edge(e));
  });
  return simplified;
}

/*
 * Finds where a line starting at point ({x, y}) would intersect a rectangle
 * ({x, y, width, height}) if it were pointing at the rectangle's center.
 */
function intersectRect(rect, point) {
  var x = rect.x;
  var y = rect.y;

  // Rectangle intersection algorithm from:
  // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  var dx = point.x - x;
  var dy = point.y - y;
  var w = rect.width / 2;
  var h = rect.height / 2;

  if (!dx && !dy) {
    throw new Error('Not possible to find intersection inside of the rectangle');
  }

  var sx, sy;
  if (Math.abs(dy) * w > Math.abs(dx) * h) {
    // Intersection is top or bottom of rect.
    if (dy < 0) {
      h = -h;
    }
    sx = (h * dx) / dy;
    sy = h;
  } else {
    // Intersection is left or right of rect.
    if (dx < 0) {
      w = -w;
    }
    sx = w;
    sy = (w * dy) / dx;
  }

  return { x: x + sx, y: y + sy };
}

/*
 * Given a DAG with each node assigned "rank" and "order" properties, this
 * function will produce a matrix with the ids of each node.
 */
function buildLayerMatrix(g) {
  var layering = map.default(range.default(maxRank(g) + 1), function () {
    return [];
  });
  forEach.default(g.nodes(), function (v) {
    var node = g.node(v);
    var rank = node.rank;
    if (!isUndefined.default(rank)) {
      layering[rank][node.order] = v;
    }
  });
  return layering;
}

/*
 * Adjusts the ranks for all nodes in the graph such that all nodes v have
 * rank(v) >= 0 and at least one node w has rank(w) = 0.
 */
function normalizeRanks(g) {
  var min$1 = min.default(
    map.default(g.nodes(), function (v) {
      return g.node(v).rank;
    }),
  );
  forEach.default(g.nodes(), function (v) {
    var node = g.node(v);
    if (has.default(node, 'rank')) {
      node.rank -= min$1;
    }
  });
}

function removeEmptyRanks(g) {
  // Ranks may not start at 0, so we need to offset them
  var offset = min.default(
    map.default(g.nodes(), function (v) {
      return g.node(v).rank;
    }),
  );

  var layers = [];
  forEach.default(g.nodes(), function (v) {
    var rank = g.node(v).rank - offset;
    if (!layers[rank]) {
      layers[rank] = [];
    }
    layers[rank].push(v);
  });

  var delta = 0;
  var nodeRankFactor = g.graph().nodeRankFactor;
  forEach.default(layers, function (vs, i) {
    if (isUndefined.default(vs) && i % nodeRankFactor !== 0) {
      --delta;
    } else if (delta) {
      forEach.default(vs, function (v) {
        g.node(v).rank += delta;
      });
    }
  });
}

function addBorderNode(g, prefix, rank, order) {
  var node = {
    width: 0,
    height: 0,
  };
  if (arguments.length >= 4) {
    node.rank = rank;
    node.order = order;
  }
  return addDummyNode(g, 'border', node, prefix);
}

function maxRank(g) {
  return max.default(
    map.default(g.nodes(), function (v) {
      var rank = g.node(v).rank;
      if (!isUndefined.default(rank)) {
        return rank;
      }
    }),
  );
}

/*
 * Partition a collection into two groups: `lhs` and `rhs`. If the supplied
 * function returns true for an entry it goes into `lhs`. Otherwise it goes
 * into `rhs.
 */
function partition(collection, fn) {
  var result = { lhs: [], rhs: [] };
  forEach.default(collection, function (value) {
    if (fn(value)) {
      result.lhs.push(value);
    } else {
      result.rhs.push(value);
    }
  });
  return result;
}

function notime(name, fn) {
  return fn();
}

exports.addBorderNode = addBorderNode;
exports.addDummyNode = addDummyNode;
exports.asNonCompoundGraph = asNonCompoundGraph;
exports.buildLayerMatrix = buildLayerMatrix;
exports.intersectRect = intersectRect;
exports.maxRank = maxRank;
exports.normalizeRanks = normalizeRanks;
exports.notime = notime;
exports.partition = partition;
exports.removeEmptyRanks = removeEmptyRanks;
exports.simplify = simplify;
