import uniqwith from 'lodash/uniqWith';
import isequal from 'lodash/isEqual';
import flatten from 'lodash/flatten';
import _get from 'lodash/get';
import moment from 'moment';
import { compareDate, itemHandlerCreator } from '../../utils';

export const clearKdFilter = model => (
  model && model.clearSortOrder
    ? model.clearSortOrder()
    : model.clearSelected()
);

export const resetKdModel = ({ items }) => {
  items.forEach(
    ({ kdFilterOptions: { model } }) => clearKdFilter(model)
  );
  return [];
};

const compareModelValues = (a, b) => (
  (moment.isMoment(a) || moment.isMoment(b)) ? compareDate(a, b) : isequal(a, b)
);

export const updateKdItem = (item, single = false, limit) => {
  const { kdFilterOptions: { model, operator, itemHandler }, value, label } = item;
  let kdItem;
  let selectedItems = [];
  if (model.addSortOrderItem) {
    kdItem = { direction: item.direction, propertyName: value };
    selectedItems = model.getSortOrderModelValue();
  } else {
    const entityType = model.getEntityType();
    kdItem = itemHandler({
      value,
      label,
      operator,
      entityType,
    });
    if (!single) {
      selectedItems = model.getSelected();
    }
  }
  const items = flatten(uniqwith([...selectedItems, kdItem], compareModelValues));
  model.setSelected(items.slice(-limit), operator);

  return item;
};

export const updateKdItems = (items, model) => {
  let selecteds = [];
  let operator;
  if (items && items.length) {
    selecteds = items.map(
      ({ value, label, direction }) => {
        if (model.addSortOrderItem) {
          return { direction, propertyName: value };
        } else {
          const entityType = model.getEntityType();
          operator = _get(model.getFilterItemValue(), 'Operator', 'Eq');
          const itemHandler = itemHandlerCreator(model.getDataType());
          return itemHandler({
            value,
            label,
            operator,
            entityType,
          });
        }
      });
  }
  model.setSelected(selecteds, operator);
  return items;
};

export const removeItemKdModel = ({ items, removedItem }) => {
  if (removedItem) {
    const { kdFilterOptions: { model } } = removedItem;
    if (model) {
      if (items.length) {
        resetKdModel({ items });
        items.forEach(item => updateKdItem(item));
      } else {
        resetKdModel({ items: [removedItem] });
      }
    }
  }
  return items;
};


export const updateKdModel = ({ items, isSingle = false }) => {
  if (items && items.length) {
    items.forEach(item => updateKdItem(item, isSingle, items.length));
  }
  return items;
};
