import * as JsSearch from 'js-search';

export function returnDataSet(uniqueField, indexFields, data) {
  const dataSet = new JsSearch.Search(uniqueField);
  dataSet.indexStrategy = new JsSearch.PrefixIndexStrategy();
  dataSet.sanitizer = new JsSearch.LowerCaseSanitizer();
  indexFields.forEach((index) => {
    dataSet.addIndex(index);
  });
  dataSet.addDocuments(data.default);
  return dataSet;
}

export function filterByKey(key, value) {
  return function filterBy(item) {
    if (item[key] === value) return item;
    return false;
  };
}

export function sortStringOn(key) {
  return function sortString(a, b) {
    const stringA = a[key].toUpperCase();
    const stringB = b[key].toUpperCase();

    let comparison = 0;

    if (stringA > stringB) {
      comparison = 1;
    } else if (stringA < stringB) {
      comparison = -1;
    }

    return comparison;
  };
}

export function sortDateOn(key) {
  return function sortDate(a, b) {
    const dateA = new Date(a[key]);
    const dateB = new Date(b[key]);
    let comparison = 0;

    if (dateA > dateB) {
      comparison = -1;
    } else if (dateA < dateB) {
      comparison = 1;
    }

    return comparison;
  };
}

export function sortIntOn(key) {
  return function sortInt(a, b) {
    const intA = a[key];
    const intB = b[key];

    return intA - intB;
  };
}
