import moment from 'moment';

// reusable sort comparator functions

/**
 * Get the property from the object, even if Immutable.
 *
 * @param {Object} obj object to get property from
 * @param {Array<string>} props search order for name of property
 * @param {*} notSetValue default value
 * @returns {*} the property
 */
function extract(obj, prop, notSetValue) {
  if (obj instanceof Object && prop in obj) {
    return obj[prop] || notSetValue
  }
  return notSetValue
}

// locale safe comparision
function string(a, b) {
  return a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase());
}

// numeric descending
function number(a, b) {
  return a === b ? 0 : a > b ? -1 : 1;
}

// date descending
function date(a, b) {
  return number(moment(a).valueOf(), moment(b).valueOf());
}

function filesize(a, b) {
  return number(
    extract(a, 'filesize', 0),
    extract(b, 'filesize', 0)
  );
}

function name(a, b) {
  let av = extract(a, 'name', '000');
  let bv = extract(b, 'name', '000');
  return string(av, bv);
}

function type(a, b) {
  let av = extract(a, 'type', '000');
  let bv = extract(b, 'type', '000');
  return string(av, bv);
}

function updatedAt(a, b) {
  return date(
    extract(a, 'updatedAt', 0),
    extract(b, 'updatedAt', 0)
  );
}

function createdAt(a, b) {
  return date(
    extract(a, 'createdAt', 0),
    extract(b, 'createdAt', 0)
  );
}

export default {
  string,
  number,
  date,
  filesize,
  name,
  type,
  updatedAt,
  createdAt
};
