import { partition } from '../util.mjs';
import sortBy from '../../../../../../lodash-es@4.17.23/node_modules/lodash-es/sortBy.mjs';
import forEach from '../../../../../../lodash-es@4.17.23/node_modules/lodash-es/forEach.mjs';
import flatten from '../../../../../../lodash-es@4.17.23/node_modules/lodash-es/flatten.mjs';
import last from '../../../../../../lodash-es@4.17.23/node_modules/lodash-es/last.mjs';

function sort(entries, biasRight) {
  var parts = partition(entries, function (entry) {
    return Object.prototype.hasOwnProperty.call(entry, 'barycenter');
  });
  var sortable = parts.lhs,
    unsortable = sortBy(parts.rhs, function (entry) {
      return -entry.i;
    }),
    vs = [],
    sum = 0,
    weight = 0,
    vsIndex = 0;

  sortable.sort(compareWithBias(!!biasRight));

  vsIndex = consumeUnsortable(vs, unsortable, vsIndex);

  forEach(sortable, function (entry) {
    vsIndex += entry.vs.length;
    vs.push(entry.vs);
    sum += entry.barycenter * entry.weight;
    weight += entry.weight;
    vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  });

  var result = { vs: flatten(vs) };
  if (weight) {
    result.barycenter = sum / weight;
    result.weight = weight;
  }
  return result;
}

function consumeUnsortable(vs, unsortable, index) {
  var last$1;
  while (unsortable.length && (last$1 = last(unsortable)).i <= index) {
    unsortable.pop();
    vs.push(last$1.vs);
    index++;
  }
  return index;
}

function compareWithBias(bias) {
  return function (entryV, entryW) {
    if (entryV.barycenter < entryW.barycenter) {
      return -1;
    } else if (entryV.barycenter > entryW.barycenter) {
      return 1;
    }

    return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
  };
}

export { sort };
