'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var byColumn = function byColumn(_ref) {
  var sortingColumns = _ref.sortingColumns;
  var selectedColumn = _ref.selectedColumn;

  var sortingColumn = sortingColumns && sortingColumns.length ? sortingColumns[0] : {};
  var sort = 'asc';

  if (sortingColumn.property === selectedColumn) {
    sort = cycleSort(sortingColumn.sort);

    if (!sort) {
      return [];
    }
  }

  return [{
    property: selectedColumn,
    sort: sort
  }];
};

var byColumns = function byColumns(_ref2) {
  var sortingColumns = _ref2.sortingColumns;
  var selectedColumn = _ref2.selectedColumn;

  var index = sortingColumns && sortingColumns.map(function (c) {
    return c.property;
  }).indexOf(selectedColumn);
  var newSortingColumns = [];

  if (!sortingColumns) {
    return [{
      property: selectedColumn,
      sort: 'asc'
    }];
  } else if (index >= 0) {
    newSortingColumns = sortingColumns;

    var newSort = cycleSort(newSortingColumns[index].sort);

    if (newSort) {
      newSortingColumns[index] = {
        property: selectedColumn,
        sort: newSort
      };
    } else {
      newSortingColumns.splice(index, 1);
    }

    return newSortingColumns;
  }

  return [].concat(_toConsumableArray(sortingColumns), [{
    property: selectedColumn,
    sort: 'asc'
  }]);
};

function cycleSort(sort) {
  return sort === 'asc' && 'desc';
}

// sorter === lodash orderBy
// https://lodash.com/docs#orderBy
var sorter = function sorter(_ref3) {
  var data = _ref3.data;
  var sortingColumns = _ref3.sortingColumns;
  var sort = _ref3.sort;

  if (!sortingColumns) {
    return data;
  }

  var propertyList = [];
  var orderList = [];

  sortingColumns.forEach(function (column) {
    propertyList.push(function (row) {
      var value = (0, _get2.default)(row, column.property);

      if (value.toLowerCase) {
        return value.toLowerCase();
      }

      return value;
    });
    orderList.push(column.sort);
  });

  return sort(data, propertyList, orderList);
};

exports.default = {
  byColumn: byColumn,
  byColumns: byColumns,
  sorter: sorter
};