'use strict';

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.slice.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.regexp.exec.js');
require('core-js/modules/es.string.search.js');
require('core-js/modules/web.dom-collections.for-each.js');
var React = require('react');
var PropTypes = require('prop-types');
var DragAndDropUtils = require('../../../utils/DragAndDropUtils.js');
var List = require('../List.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var itemPropTypes = {
  id: PropTypes__default.default.string,
  content: PropTypes__default.default.shape({
    value: PropTypes__default.default.string,
    icon: PropTypes__default.default.node
  }),
  children: PropTypes__default.default.arrayOf(PropTypes__default.default.any),
  // TODO: make this recursive
  isSelectable: PropTypes__default.default.bool
};
var propTypes = {
  /** list title */
  title: PropTypes__default.default.string.isRequired,
  /** use search with default behavior */
  hasSearch: PropTypes__default.default.bool,
  /** action buttons on right side of list title */
  buttons: PropTypes__default.default.arrayOf(PropTypes__default.default.node),
  /** list editing style */
  editingStyle: PropTypes__default.default.oneOf([DragAndDropUtils.EditingStyle.Single, DragAndDropUtils.EditingStyle.Multiple, DragAndDropUtils.EditingStyle.SingleNesting, DragAndDropUtils.EditingStyle.MultipleNesting]),
  /** data source of list items */
  items: PropTypes__default.default.arrayOf(PropTypes__default.default.shape(itemPropTypes)).isRequired,
  /** use full height in list */
  isFullHeight: PropTypes__default.default.bool,
  /** use large/fat row in list */
  isLargeRow: PropTypes__default.default.bool,
  /** optional skeleton to be rendered while loading data */
  isLoading: PropTypes__default.default.bool,
  /** i18n strings */
  i18n: PropTypes__default.default.shape({
    searchPlaceHolderText: PropTypes__default.default.string,
    pageOfPagesText: PropTypes__default.default.func,
    expand: PropTypes__default.default.string,
    close: PropTypes__default.default.string
  }),
  /** pageSize */
  pageSize: PropTypes__default.default.string,
  /** callback function returned a modified list */
  onListUpdated: PropTypes__default.default.func,
  /** optionally renders SimplePagination at the bottom of the list */
  hasPagination: PropTypes__default.default.bool,
  /** Optional callback when a item is selected.
   * OnSelect(itemId, parentItemId)
   */
  onSelect: PropTypes__default.default.func,
  testId: PropTypes__default.default.string,
  /** content shown if list is empty on search */
  emptySearchState: PropTypes__default.default.oneOfType([PropTypes__default.default.node, PropTypes__default.default.string])
};
var defaultProps = {
  buttons: [],
  editingStyle: null,
  hasSearch: false,
  onListUpdated: function onListUpdated() {},
  i18n: {
    searchPlaceHolderText: 'Enter a value',
    pageOfPagesText: function pageOfPagesText(page) {
      return "Page ".concat(page);
    },
    items: '%d items'
  },
  isLargeRow: false,
  isFullHeight: false,
  isLoading: false,
  pageSize: null,
  hasPagination: true,
  onSelect: null,
  testId: 'simple-list',
  emptySearchState: 'No results found'
};
var SimpleList = function SimpleList(_ref) {
  var buttons = _ref.buttons,
    editingStyle = _ref.editingStyle,
    hasSearch = _ref.hasSearch,
    i18n = _ref.i18n,
    isFullHeight = _ref.isFullHeight,
    isLargeRow = _ref.isLargeRow,
    isLoading = _ref.isLoading,
    items = _ref.items,
    onListUpdated = _ref.onListUpdated,
    pageSize = _ref.pageSize,
    hasPagination = _ref.hasPagination,
    onSelect = _ref.onSelect,
    title = _ref.title,
    testId = _ref.testId,
    emptySearchState = _ref.emptySearchState;
  var mergedI18n = React.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var _useState = React.useState([]),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    selectedIds = _useState2[0],
    setSelectedIds = _useState2[1];
  var _useState3 = React.useState(''),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    searchValue = _useState4[0],
    setSearchValue = _useState4[1];
  var _useState5 = React.useState(items),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    filteredItems = _useState6[0],
    setFilteredItems = _useState6[1];
  var _useState7 = React.useState([]),
    _useState8 = _slicedToArray__default.default(_useState7, 2),
    editModeSelectedIds = _useState8[0],
    setEditModeSelectedIds = _useState8[1];
  var _useState9 = React.useState(1),
    _useState10 = _slicedToArray__default.default(_useState9, 2),
    currentPageNumber = _useState10[0],
    setCurrentPageNumber = _useState10[1];
  var numberOfItems = filteredItems.length;
  var rowPerPage = React.useMemo(function () {
    if (!hasPagination) {
      return numberOfItems;
    }
    switch (pageSize) {
      case 'sm':
        return 5;
      case 'lg':
        return 10;
      case 'xl':
      default:
        return 20;
    }
  }, [hasPagination, numberOfItems, pageSize]);
  var _useState11 = React.useState(filteredItems.slice(0, rowPerPage)),
    _useState12 = _slicedToArray__default.default(_useState11, 2),
    itemsToShow = _useState12[0],
    setItemsToShow = _useState12[1];
  var handleSearch = React.useCallback(function (searchTerm) {
    setSearchValue(searchTerm);
    var searchFilteredItems = items.filter(function (item) {
      if (item.content.value !== '' && item.content.value !== undefined) {
        if (typeof item.content.secondaryValue === 'string' && item.content.secondaryValue !== '') {
          return item.content.value.toLowerCase().search(searchTerm.toLowerCase()) !== -1 || item.content.secondaryValue.toLowerCase().search(searchTerm.toLowerCase()) !== -1;
        }
        return item.content.value.toLowerCase().search(searchTerm.toLowerCase()) !== -1;
      }
      return false;
    });
    setFilteredItems(searchFilteredItems);
    setSearchValue(searchTerm);
    if (pageSize !== null) {
      setItemsToShow(searchFilteredItems.slice(0, rowPerPage));
    }
  }, [items, pageSize, rowPerPage]);
  var onPage = React.useCallback(function (page) {
    var rowUpperLimit = page * rowPerPage;
    var currentItemsOnPage = filteredItems.slice(rowUpperLimit - rowPerPage, rowUpperLimit);
    setCurrentPageNumber(page);
    setItemsToShow(currentItemsOnPage);
  }, [filteredItems, rowPerPage]);
  var maxPage = Math.ceil(numberOfItems / rowPerPage);

  /**
   * When the items array updates, make sure to update the filteredItems, but also re-apply
   * search values if there were any.
   */
  React.useEffect(function () {
    setFilteredItems(items);
    if (searchValue) {
      handleSearch(searchValue);
    }
  }, [items, handleSearch, searchValue]);

  /**
   * to maintain the correct page and items from that page, we must update the
   * itemsToShow array based on the current page and the number of rows shown based on
   * the pageSize prop.
   */
  React.useEffect(function () {
    var startIndex = (currentPageNumber - 1) * rowPerPage;
    setItemsToShow(filteredItems.slice(startIndex, startIndex + rowPerPage));
  }, [currentPageNumber, filteredItems, rowPerPage]);

  /**
   * If we were on a higher page and the number of items drop, we need to ensure we
   * reset to the first page when the number of items drops below our previous max page.
   */
  React.useEffect(function () {
    if (currentPageNumber > maxPage) {
      onPage(1);
    }
  }, [currentPageNumber, maxPage, onPage, pageSize]);
  var handleSelect = function handleSelect(id, parentId) {
    if (editingStyle) {
      setEditModeSelectedIds(DragAndDropUtils.handleEditModeSelect(items, editModeSelectedIds, id, parentId));
    } else {
      setSelectedIds(selectedIds.indexOf(id) !== -1 ? selectedIds.filter(function (item) {
        return item !== id;
      }) : [].concat(_toConsumableArray__default.default(selectedIds), [id]));
      if (onSelect) {
        onSelect(id, parentId);
      }
    }
  };
  var onItemMoved = function onItemMoved(dragId, hoverId, target) {
    var updatedList;
    if (editModeSelectedIds.length > 0 && editModeSelectedIds.find(function (selectionId) {
      return selectionId === dragId;
    })) {
      updatedList = DragAndDropUtils.moveItemsInList(items, editModeSelectedIds, hoverId, target);
    } else {
      updatedList = DragAndDropUtils.moveItemsInList(items, [dragId], hoverId, target);
    }
    onListUpdated(updatedList);
    setFilteredItems(updatedList);
  };
  return /*#__PURE__*/React__default.default.createElement(List.default, {
    title: title,
    search: hasSearch ? {
      value: searchValue,
      onChange: function onChange(evt) {
        handleSearch(evt.target.value);
      }
    } : null,
    buttons: buttons,
    i18n: mergedI18n,
    isFullHeight: isFullHeight,
    items: pageSize !== null ? itemsToShow : filteredItems,
    pagination: hasPagination ? {
      page: currentPageNumber,
      onPage: onPage,
      maxPage: maxPage,
      pageOfPagesText: function pageOfPagesText(page) {
        return mergedI18n.pageOfPagesText(page);
      }
    } : null,
    selectedIds: editingStyle ? editModeSelectedIds : selectedIds,
    handleSelect: handleSelect,
    isFiltering: !!searchValue,
    isLargeRow: isLargeRow,
    isLoading: isLoading,
    editingStyle: editingStyle,
    onItemMoved: onItemMoved,
    testId: testId,
    emptySearchState: emptySearchState
  });
};
SimpleList.propTypes = propTypes;
SimpleList.defaultProps = defaultProps;
SimpleList.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "SimpleList",
  "props": {
    "buttons": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "action buttons on right side of list title",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "node"
        }
      },
      "required": false
    },
    "editingStyle": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "list editing style",
      "type": {
        "name": "enum",
        "value": [{
          "value": "EditingStyle.Single",
          "computed": true
        }, {
          "value": "EditingStyle.Multiple",
          "computed": true
        }, {
          "value": "EditingStyle.SingleNesting",
          "computed": true
        }, {
          "value": "EditingStyle.MultipleNesting",
          "computed": true
        }]
      },
      "required": false
    },
    "hasSearch": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "use search with default behavior",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "onListUpdated": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "description": "callback function returned a modified list",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  searchPlaceHolderText: 'Enter a value',\n  pageOfPagesText: (page) => `Page ${page}`,\n  items: '%d items',\n}",
        "computed": false
      },
      "description": "i18n strings",
      "type": {
        "name": "shape",
        "value": {
          "searchPlaceHolderText": {
            "name": "string",
            "required": false
          },
          "pageOfPagesText": {
            "name": "func",
            "required": false
          },
          "expand": {
            "name": "string",
            "required": false
          },
          "close": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "isLargeRow": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "use large/fat row in list",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isFullHeight": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "use full height in list",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isLoading": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "optional skeleton to be rendered while loading data",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "pageSize": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "pageSize",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "hasPagination": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "description": "optionally renders SimplePagination at the bottom of the list",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "onSelect": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Optional callback when a item is selected.\nOnSelect(itemId, parentItemId)",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'simple-list'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "emptySearchState": {
      "defaultValue": {
        "value": "'No results found'",
        "computed": false
      },
      "description": "content shown if list is empty on search",
      "type": {
        "name": "union",
        "value": [{
          "name": "node"
        }, {
          "name": "string"
        }]
      },
      "required": false
    },
    "title": {
      "description": "list title",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "items": {
      "description": "data source of list items",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "id": {
              "name": "string",
              "required": false
            },
            "content": {
              "name": "shape",
              "value": {
                "value": {
                  "name": "string",
                  "required": false
                },
                "icon": {
                  "name": "node",
                  "required": false
                }
              },
              "required": false
            },
            "children": {
              "name": "arrayOf",
              "value": {
                "name": "any"
              },
              "required": false
            },
            "isSelectable": {
              "name": "bool",
              "required": false
            }
          }
        }
      },
      "required": true
    }
  }
};
var SimpleList$1 = SimpleList;

module.exports = SimpleList$1;
