'use strict';

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var isEqual = require('../../../node_modules/lodash-es/isEqual.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.array.sort.js');
require('core-js/modules/es.array.splice.js');
require('core-js/modules/es.function.name.js');
require('core-js/modules/es.object.assign.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/web.dom-collections.for-each.js');
var React = require('react');
var PropTypes = require('prop-types');
var update = require('immutability-helper');
var Button = require('../../Button/Button.js');
var ComposedModal = require('../../ComposedModal/ComposedModal.js');
var Settings = require('../../../constants/Settings.js');
var TablePropTypes = require('../TablePropTypes.js');
var DragAndDropUtils = require('../../../utils/DragAndDropUtils.js');
var TableMultiSortRow = require('./TableMultiSortRow.js');

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

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

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 iotPrefix = Settings.settings.iotPrefix,
  prefix = Settings.settings.prefix;
var propTypes = {
  columns: TablePropTypes.TableColumnsPropTypes.isRequired,
  ordering: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
    columnId: PropTypes__default.default.string.isRequired,
    /* Visibility of column in table, defaults to false */
    isHidden: PropTypes__default.default.bool
  })).isRequired,
  actions: PropTypes__default.default.shape({
    onAddMultiSortColumn: PropTypes__default.default.func,
    onRemoveMultiSortColumn: PropTypes__default.default.func,
    onSaveMultiSortColumns: PropTypes__default.default.func,
    onCancelMultiSortColumns: PropTypes__default.default.func,
    onClearMultiSortColumns: PropTypes__default.default.func
  }).isRequired,
  sort: PropTypes__default.default.oneOfType([TablePropTypes.TableSortPropType, PropTypes__default.default.arrayOf(TablePropTypes.TableSortPropType)]).isRequired,
  showMultiSortModal: PropTypes__default.default.bool,
  i18n: PropTypes__default.default.shape({
    multiSortModalTitle: PropTypes__default.default.string,
    multiSortModalPrimaryLabel: PropTypes__default.default.string,
    multiSortModalSecondaryLabel: PropTypes__default.default.string,
    multiSortModalClearLabel: PropTypes__default.default.string,
    multiSortSelectColumnLabel: PropTypes__default.default.string,
    multiSortSelectColumnSortByTitle: PropTypes__default.default.string,
    multiSortSelectColumnThenByTitle: PropTypes__default.default.string,
    multiSortDirectionLabel: PropTypes__default.default.string,
    multiSortDirectionTitle: PropTypes__default.default.string,
    multiSortAddColumn: PropTypes__default.default.string,
    multiSortRemoveColumn: PropTypes__default.default.string,
    multiSortAscending: PropTypes__default.default.string,
    multiSortDescending: PropTypes__default.default.string,
    multiSortCloseModal: PropTypes__default.default.string,
    multiSortOpenMenu: PropTypes__default.default.string,
    multiSortCloseMenu: PropTypes__default.default.string,
    multiSortDragHandle: PropTypes__default.default.string
  }),
  testId: PropTypes__default.default.string
};
var defaultProps = {
  showMultiSortModal: false,
  i18n: {
    multiSortModalTitle: 'Select columns to sort',
    multiSortModalPrimaryLabel: 'Sort',
    multiSortModalSecondaryLabel: 'Cancel',
    multiSortModalClearLabel: 'Clear sorting',
    multiSortSelectColumnLabel: 'Select a column',
    multiSortSelectColumnSortByTitle: 'Sort by',
    multiSortSelectColumnThenByTitle: 'Then by',
    multiSortDirectionLabel: 'Select a direction',
    multiSortDirectionTitle: 'Sort order',
    multiSortAddColumn: 'Add column',
    multiSortRemoveColumn: 'Remove column',
    multiSortAscending: 'Ascending',
    multiSortDescending: 'Descending',
    multiSortCloseModal: 'Close',
    multiSortDragHandle: 'Drag handle'
  },
  testId: 'multi-sort-modal'
};

/**
 * Simple helper function to turn the sort object into an array and filter empty values from it
 * @param {Array|Object} sort A sort object or an array of sort objects
 * @returns Array
 */
var cleanSortArray = function cleanSortArray(sort) {
  var sortArray = Array.isArray(sort) ? sort : sort !== undefined ? [sort] : [];
  return sortArray.filter(function (_ref) {
    var columnId = _ref.columnId;
    return columnId;
  });
};
var TableMultiSortModal = function TableMultiSortModal(_ref2) {
  var columns = _ref2.columns,
    ordering = _ref2.ordering,
    sort = _ref2.sort,
    actions = _ref2.actions,
    showMultiSortModal = _ref2.showMultiSortModal,
    i18n = _ref2.i18n,
    testId = _ref2.testId;
  var onAddMultiSortColumn = actions.onAddMultiSortColumn,
    onRemoveMultiSortColumn = actions.onRemoveMultiSortColumn,
    onSaveMultiSortColumns = actions.onSaveMultiSortColumns,
    onCancelMultiSortColumns = actions.onCancelMultiSortColumns,
    onClearMultiSortColumns = actions.onClearMultiSortColumns;
  var sortHelper = React.useCallback(function () {
    var sortArray = cleanSortArray(sort);
    if (!sortArray.length) {
      return [{
        columnId: '',
        direction: 'ASC'
      }];
    }
    return sortArray;
  }, [sort]);
  var _useState = React.useState(sortHelper),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    selectedMultiSortColumns = _useState2[0],
    setSelectedMultiSortColumns = _useState2[1];
  React.useEffect(function () {
    setSelectedMultiSortColumns(sortHelper);
  }, [sort, sortHelper]);
  var sortDirections = React.useMemo(function () {
    return [{
      id: 'ASC',
      label: i18n.multiSortAscending
    }, {
      id: 'DESC',
      label: i18n.multiSortDescending
    }];
  }, [i18n.multiSortAscending, i18n.multiSortDescending]);
  var handleSelectMultiSortColumn = function handleSelectMultiSortColumn(index) {
    return function (event) {
      var columnId = event.target.value;
      setSelectedMultiSortColumns(function (prev) {
        var currentItem = prev[index];
        return Object.assign([], prev, _defineProperty__default.default({}, index, _objectSpread(_objectSpread({}, currentItem), {}, {
          columnId: columnId
        })));
      });
    };
  };
  var handleSelectMultiSortColumnDirection = function handleSelectMultiSortColumnDirection(index) {
    return function (event) {
      var direction = event.target.value;
      setSelectedMultiSortColumns(function (prev) {
        var currentItem = prev[index];
        return Object.assign([], prev, _defineProperty__default.default({}, index, _objectSpread(_objectSpread({}, currentItem), {}, {
          direction: direction
        })));
      });
    };
  };
  var multiSortColumns = React.useMemo(function () {
    return columns.filter(function (_ref3) {
      var id = _ref3.id,
        isSortable = _ref3.isSortable;
      var orderCol = ordering.find(function (_ref4) {
        var columnId = _ref4.columnId;
        return columnId === id;
      });
      return isSortable && !orderCol.isHidden;
    }).map(function (col) {
      var columnAlreadySorted = selectedMultiSortColumns.find(function (_ref5) {
        var columnId = _ref5.columnId;
        return columnId === col.id;
      }) !== undefined;
      return {
        id: col.id,
        name: col.name,
        disabled: columnAlreadySorted
      };
    });
  }, [columns, ordering, selectedMultiSortColumns]);
  var getInitialSelectedColumn = function getInitialSelectedColumn(columnId) {
    var selectedColumn = columns.find(function (col) {
      return col.id === columnId;
    });
    return selectedColumn || multiSortColumns.filter(function (col) {
      return !col.disabled;
    })[0];
  };
  var getInitialSelectedDirection = function getInitialSelectedDirection(direction) {
    var selectedDirection = sortDirections.find(function (dir) {
      return dir.id === direction;
    });
    return selectedDirection || sortDirections[0];
  };
  var handleAddMultiSortColumn = function handleAddMultiSortColumn(index) {
    return function () {
      setSelectedMultiSortColumns(function (prev) {
        var _multiSortColumns$fil2;
        var clone = _toConsumableArray__default.default(prev);
        var nextColumnIndex = 0;
        // If the default column is in the first position, set it before adding the next column
        if (clone.length === 1 && Object.keys(clone[0]).length === 0) {
          var _multiSortColumns$fil;
          clone.splice(index, 1, {
            columnId: (_multiSortColumns$fil = multiSortColumns.filter(function (col) {
              return !col.disabled;
            })[nextColumnIndex]) === null || _multiSortColumns$fil === void 0 ? void 0 : _multiSortColumns$fil.id,
            direction: 'ASC'
          });
          nextColumnIndex = 1;
        }
        clone.splice(index + 1, 0, {
          columnId: (_multiSortColumns$fil2 = multiSortColumns.filter(function (col) {
            return !col.disabled;
          })[nextColumnIndex]) === null || _multiSortColumns$fil2 === void 0 ? void 0 : _multiSortColumns$fil2.id,
          direction: 'ASC'
        });
        return clone;
      });
      onAddMultiSortColumn(index);
    };
  };
  var handleRemoveMultiSortColumn = function handleRemoveMultiSortColumn(index) {
    return function () {
      setSelectedMultiSortColumns(function (prev) {
        return prev.filter(function (c, i) {
          return i !== index;
        });
      });
      onRemoveMultiSortColumn(index);
    };
  };
  var handleSaveMultiSortColumns = function handleSaveMultiSortColumns() {
    // if empty strings were passed for columnId or direction
    // the dropdown will show the first available column and direction,
    // but if they save without performing a change, the initial state
    // is empty, so we perform a check to ensure the defaults are saved
    var defaulted = selectedMultiSortColumns.map(function (_ref6) {
      var columnId = _ref6.columnId,
        direction = _ref6.direction;
      var column = getInitialSelectedColumn(columnId);
      var dir = getInitialSelectedDirection(direction);
      return {
        columnId: columnId || column.id,
        direction: direction || dir.id
      };
    });
    if (!isEqual(selectedMultiSortColumns, defaulted)) {
      setSelectedMultiSortColumns(defaulted);
    }
    onSaveMultiSortColumns(defaulted);
  };
  var handleCancelMultiSortColumns = function handleCancelMultiSortColumns() {
    setSelectedMultiSortColumns(cleanSortArray(sort));
    onCancelMultiSortColumns();
  };
  var handleClearMultiSortColumns = function handleClearMultiSortColumns() {
    setSelectedMultiSortColumns([]);
    onClearMultiSortColumns();
  };
  var onMoveRow = React.useCallback(function (dragIndex, hoverIndex) {
    setSelectedMultiSortColumns(function (prev) {
      var row = prev[dragIndex];
      return update__default.default(prev, {
        $splice: [[dragIndex, 1], [hoverIndex, 0, row]]
      });
    });
  }, []);
  return /*#__PURE__*/React__default.default.createElement(ComposedModal.default, {
    selectorPrimaryFocus: ".".concat(prefix, "--modal-header"),
    testId: testId,
    className: "".concat(iotPrefix, "--table-multi-sort-modal"),
    header: {
      title: i18n.multiSortModalTitle
    },
    iconDescription: i18n.multiSortCloseModal,
    onClose: handleCancelMultiSortColumns,
    footer: /*#__PURE__*/React__default.default.createElement("div", {
      className: "".concat(iotPrefix, "--table-multi-sort-modal__footer")
    }, /*#__PURE__*/React__default.default.createElement(Button, {
      kind: "ghost",
      onClick: handleClearMultiSortColumns,
      testId: "".concat(testId, "-modal-clear-button")
    }, i18n.multiSortModalClearLabel), /*#__PURE__*/React__default.default.createElement("div", null), /*#__PURE__*/React__default.default.createElement(Button, {
      kind: "secondary",
      onClick: handleCancelMultiSortColumns,
      testId: "".concat(testId, "-modal-secondary-button")
    }, i18n.multiSortModalSecondaryLabel), /*#__PURE__*/React__default.default.createElement(Button, {
      kind: "primary",
      onClick: handleSaveMultiSortColumns,
      testId: "".concat(testId, "-modal-primary-button"),
      "data-modal-primary-focus": true
    }, i18n.multiSortModalPrimaryLabel)),
    open: showMultiSortModal
  }, /*#__PURE__*/React__default.default.createElement(DragAndDropUtils.DragAndDrop, null, selectedMultiSortColumns.map(function (_ref7, index) {
    var columnId = _ref7.columnId,
      direction = _ref7.direction;
    var defaultColumn = getInitialSelectedColumn(columnId);
    var defaultDirection = getInitialSelectedDirection(direction);
    return /*#__PURE__*/React__default.default.createElement(TableMultiSortRow.TableMultiSortRow, {
      key: "".concat(columnId, "-").concat(direction),
      columnId: columnId || (defaultColumn === null || defaultColumn === void 0 ? void 0 : defaultColumn.id),
      defaultColumnId: defaultColumn === null || defaultColumn === void 0 ? void 0 : defaultColumn.id,
      defaultDirectionId: defaultDirection === null || defaultDirection === void 0 ? void 0 : defaultDirection.id,
      i18n: i18n,
      index: index,
      multiSortColumns: multiSortColumns,
      numSelectedColumns: selectedMultiSortColumns === null || selectedMultiSortColumns === void 0 ? void 0 : selectedMultiSortColumns.length,
      onAddMultiSortColumn: handleAddMultiSortColumn(index),
      onMoveRow: onMoveRow,
      onRemoveMultiSortColumn: handleRemoveMultiSortColumn(index),
      onSelectMultiSortColumn: handleSelectMultiSortColumn(index),
      onSelectMultiSortColumnDirection: handleSelectMultiSortColumnDirection(index),
      sortDirections: sortDirections,
      testId: testId
    });
  })));
};
TableMultiSortModal.propTypes = propTypes;
TableMultiSortModal.defaultProps = defaultProps;
TableMultiSortModal.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TableMultiSortModal",
  "props": {
    "showMultiSortModal": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  multiSortModalTitle: 'Select columns to sort',\n  multiSortModalPrimaryLabel: 'Sort',\n  multiSortModalSecondaryLabel: 'Cancel',\n  multiSortModalClearLabel: 'Clear sorting',\n  multiSortSelectColumnLabel: 'Select a column',\n  multiSortSelectColumnSortByTitle: 'Sort by',\n  multiSortSelectColumnThenByTitle: 'Then by',\n  multiSortDirectionLabel: 'Select a direction',\n  multiSortDirectionTitle: 'Sort order',\n  multiSortAddColumn: 'Add column',\n  multiSortRemoveColumn: 'Remove column',\n  multiSortAscending: 'Ascending',\n  multiSortDescending: 'Descending',\n  multiSortCloseModal: 'Close',\n  multiSortDragHandle: 'Drag handle',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "multiSortModalTitle": {
            "name": "string",
            "required": false
          },
          "multiSortModalPrimaryLabel": {
            "name": "string",
            "required": false
          },
          "multiSortModalSecondaryLabel": {
            "name": "string",
            "required": false
          },
          "multiSortModalClearLabel": {
            "name": "string",
            "required": false
          },
          "multiSortSelectColumnLabel": {
            "name": "string",
            "required": false
          },
          "multiSortSelectColumnSortByTitle": {
            "name": "string",
            "required": false
          },
          "multiSortSelectColumnThenByTitle": {
            "name": "string",
            "required": false
          },
          "multiSortDirectionLabel": {
            "name": "string",
            "required": false
          },
          "multiSortDirectionTitle": {
            "name": "string",
            "required": false
          },
          "multiSortAddColumn": {
            "name": "string",
            "required": false
          },
          "multiSortRemoveColumn": {
            "name": "string",
            "required": false
          },
          "multiSortAscending": {
            "name": "string",
            "required": false
          },
          "multiSortDescending": {
            "name": "string",
            "required": false
          },
          "multiSortCloseModal": {
            "name": "string",
            "required": false
          },
          "multiSortOpenMenu": {
            "name": "string",
            "required": false
          },
          "multiSortCloseMenu": {
            "name": "string",
            "required": false
          },
          "multiSortDragHandle": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'multi-sort-modal'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "columns": {
      "description": "",
      "type": {
        "name": "custom",
        "raw": "TableColumnsPropTypes.isRequired"
      },
      "required": false
    },
    "ordering": {
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "columnId": {
              "name": "string",
              "required": true
            },
            "isHidden": {
              "name": "bool",
              "required": false
            }
          }
        }
      },
      "required": true
    },
    "actions": {
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "onAddMultiSortColumn": {
            "name": "func",
            "required": false
          },
          "onRemoveMultiSortColumn": {
            "name": "func",
            "required": false
          },
          "onSaveMultiSortColumns": {
            "name": "func",
            "required": false
          },
          "onCancelMultiSortColumns": {
            "name": "func",
            "required": false
          },
          "onClearMultiSortColumns": {
            "name": "func",
            "required": false
          }
        }
      },
      "required": true
    },
    "sort": {
      "description": "",
      "type": {
        "name": "union",
        "value": [{
          "name": "custom",
          "raw": "TableSortPropType"
        }, {
          "name": "arrayOf",
          "value": {
            "name": "custom",
            "raw": "TableSortPropType"
          }
        }]
      },
      "required": true
    }
  }
};
var TableMultiSortModal$1 = TableMultiSortModal;

module.exports = TableMultiSortModal$1;
