import flatten from 'lodash/flatten';

export const removeItem = props => (option, remove) => {
  const {
     deleteItem,
     wrapperState: { itemsState },
     events,
   } = props;
  const items = [...itemsState];
  const index = items.findIndex(item => item.key === option);
  const removedItem = (index > -1) ? items.splice(index, 1)[0] : null;
  if (removedItem) {
    const { kdFilterOptions: { model } } = removedItem;
    const callback =
      () => {
        if (model.addSortOrderItem) {
          events && events.onChange && events.onChange({
            data: {
              ...model.getSortOrderModelValue(),
              model,
            },
          });
        } else {
          events && events.onChange && events.onChange({
            data: {
              ...model.getFilterItemValue(),
              model,
            },
          });
        }
        remove && remove(items);
      };
    deleteItem({ items, removedItem }, callback);
  }
};

export const addChicklet = props => ({
   value,
   chickletLabel,
   option,
   inputVisible,
   remove,
   category,
   direction,
   errors,
   kdFilterModel,
   kdFilterOptions = {
     model: props.kdFilterModel,
     operator: 'Eq',
     itemHandler,
   },
}, callback) => {
  const {
    setErrors,
    clearErrors,
    setOption,
    chicklets,
    removeItem,
    wrapperState: { itemsState },
    addItemSingle,
    addNewItem,
    setItems,
    isChickletNone,
    isAddChicklet,
    isAddChickletSingle,
    isAddChickletSingleRegardlessOfType,
    events,
  } = props;

  if (!value || !chickletLabel || errors) {
    if (errors) {
      console.error('Error', errors);
      setErrors({
        errors,
      });
    }
    return removeItem(option);
  }

  const newItem = {
    value,
    option,
    direction,
    label: chickletLabel,
    key: option,
    category,
    kdFilterOptions,
    chicklets,
    kdFilterModel,
    onRemove: () => {
      removeItem(option, remove);
    },
  };

  if (isChickletNone()) {
    newItem.autocompleteVisible = inputVisible;
    newItem.isChickletNone = isChickletNone();
    newItem.hasMainSelector = props.mainSelector.visible;
  }

  if (kdFilterOptions.operator === 'Eq' || kdFilterOptions.operator === 'notEq' || kdFilterOptions.operator === 'Like') {
    if (isAddChickletSingle()) {
      // fatChicklet
    }
    addNewItem({ newItem }, callback);
  } else {
    addItemSingle(newItem, callback);
  }

  setOption(option);
  clearErrors();
};


export const setChicklets = props => ({ chicklets, callback, model }) => {
  const {
    clearErrors,
    addItemSingle,
    removeItem,
    setItems,
    isChickletNone,
    valuesLimit,
  } = props;
  let items = flatten(
    chicklets.map(
      (opt) => {
        const useValues = (opt.values.length > 1);
        return opt.values.map(
          (value) => {
            return ({
              ...opt,
              value,
              label: useValues ? value : opt.chickletLabel,
              key: opt.option,
              onRemove: () => {
                removeItem(opt.option, opt.remove);
              },
            });
          },
        );
      },
    ),
  );
  if (items) {
    const item = [...items].pop();
    if (isChickletNone() || valuesLimit === 1) {
      addItemSingle({ ...item, kdFilerModel: model, value: item.values[0] });
    } else {
      setItems({ items, model, callback });
    }
    clearErrors();
  }
};

