import isequal from 'lodash.isequal';
import uniqwith from 'lodash.uniqwith';
import flatten from 'lodash.flatten';

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

export const updateKdItemPosition = () => ({ kdFilterModel, selectedItems }) =>
  (
    kdFilterModel.setSelected(
      selectedItems.map(selectedItem => (
        {
          propertyName: selectedItem.propertyName,
          direction: selectedItem.direction,
        }
      ))
    )
  );

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

export const updateKdItem = (item, single = false) => {
  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();
    }
  }
  model.setSelected(flatten(uniqwith([...selectedItems, kdItem], isequal)), operator);
  return item;
};


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


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