"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useDataGridColumnSorting = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _popover = require("../popover");
var _i18n = require("../i18n");
var _text = require("../text");
var _button = require("../button");
var _flex = require("../flex");
var _drag_and_drop = require("../drag_and_drop");
var _column_sorting_draggable = require("./column_sorting_draggable");
var _data_grid_schema = require("./data_grid_schema");
var _token = require("../token");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) { ; } } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } /*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */ /*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var useDataGridColumnSorting = function useDataGridColumnSorting(columns, sorting, schema, schemaDetectors, displayValues) {
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    avilableColumnsisOpen = _useState4[0],
    setAvailableColumnsIsOpen = _useState4[1]; // prune any non-existent/hidden columns from sorting
  (0, _react.useEffect)(function () {
    if (sorting) {
      var nextSortingColumns = [];
      var availableColumnIds = new Set(columns.map(function (_ref) {
        var id = _ref.id;
        return id;
      }));
      for (var i = 0; i < sorting.columns.length; i++) {
        var column = sorting.columns[i];
        if (availableColumnIds.has(column.id)) {
          nextSortingColumns.push(column);
        }
      }

      // if the column array lengths differ then the sorting columns have been pruned
      if (nextSortingColumns.length !== sorting.columns.length) {
        sorting.onSort(nextSortingColumns);
      }
    }
  }, [columns, sorting]);
  if (sorting == null) return [null];
  var activeColumnIds = new Set(sorting.columns.map(function (_ref2) {
    var id = _ref2.id;
    return id;
  }));
  var _columns$reduce = columns.reduce(function (acc, column) {
      if (activeColumnIds.has(column.id)) {
        acc.activeColumns.push(column);
      } else {
        acc.inactiveColumns.push(column);
      }
      return acc;
    }, {
      activeColumns: [],
      inactiveColumns: []
    }),
    inactiveColumns = _columns$reduce.inactiveColumns;
  function onDragEnd(_ref3) {
    var sourceIndex = _ref3.source.index,
      destination = _ref3.destination;
    var destinationIndex = destination.index;
    var nextColumns = (0, _drag_and_drop.euiDragDropReorder)(sorting.columns, sourceIndex, destinationIndex);
    sorting.onSort(nextColumns);
  }
  var controlBtnClasses = (0, _classnames.default)('euiDataGrid__controlBtn', {
    'euiDataGrid__controlBtn--active': sorting.columns.length > 0
  });
  var numberOfSortedFields = sorting.columns.length;
  var schemaDetails = function schemaDetails(id) {
    return schema.hasOwnProperty(id) && schema[id].columnType != null ? (0, _data_grid_schema.getDetailsForSchema)(schemaDetectors, schema[id].columnType) : null;
  };
  var inactiveSortableColumns = inactiveColumns.filter(function (_ref4) {
    var id = _ref4.id,
      isSortable = _ref4.isSortable;
    var schemaDetail = schemaDetails(id);
    var sortable = true;
    if (isSortable != null) {
      sortable = isSortable;
    } else if (schemaDetail != null) {
      sortable = schemaDetail.hasOwnProperty('isSortable') ? schemaDetail.isSortable : true;
    }
    return sortable;
  });
  var columnSorting = /*#__PURE__*/_react.default.createElement(_popover.EuiPopover, {
    "data-test-subj": "dataGridColumnSortingPopover",
    isOpen: isOpen,
    closePopover: function closePopover() {
      return setIsOpen(false);
    },
    anchorPosition: "downLeft",
    panelPaddingSize: "s",
    panelClassName: "euiDataGridColumnSortingPopover",
    button: /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
      tokens: ['euiColumnSorting.button', 'euiColumnSorting.buttonActive'],
      defaults: ['Sort fields', 'fields sorted']
    }, function (_ref5) {
      var _ref6 = _slicedToArray(_ref5, 2),
        button = _ref6[0],
        buttonActive = _ref6[1];
      return /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
        size: "xs",
        iconType: "sortable",
        color: "text",
        className: controlBtnClasses,
        "data-test-subj": "dataGridColumnSortingButton",
        onClick: function onClick() {
          return setIsOpen(!isOpen);
        }
      }, numberOfSortedFields > 0 ? "".concat(numberOfSortedFields, " ").concat(buttonActive) : button);
    })
  }, sorting.columns.length > 0 ? /*#__PURE__*/_react.default.createElement("div", {
    role: "region",
    "aria-live": "assertive",
    className: "euiDataGrid__controlScroll"
  }, /*#__PURE__*/_react.default.createElement(_drag_and_drop.EuiDragDropContext, {
    onDragEnd: onDragEnd
  }, /*#__PURE__*/_react.default.createElement(_drag_and_drop.EuiDroppable, {
    droppableId: "columnSorting"
  }, /*#__PURE__*/_react.default.createElement(_react.Fragment, null, sorting.columns.map(function (_ref7, index) {
    var id = _ref7.id,
      direction = _ref7.direction;
    return /*#__PURE__*/_react.default.createElement(_column_sorting_draggable.EuiDataGridColumnSortingDraggable, {
      key: id,
      id: id,
      display: displayValues[id],
      direction: direction,
      index: index,
      sorting: sorting,
      schema: schema,
      schemaDetectors: schemaDetectors
    });
  }))))) : /*#__PURE__*/_react.default.createElement(_text.EuiText, {
    size: "s",
    color: "subdued"
  }, /*#__PURE__*/_react.default.createElement("p", {
    role: "alert"
  }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiColumnSorting.emptySorting",
    default: "Currently no fields are sorted"
  }))), (inactiveSortableColumns.length > 0 || sorting.columns.length > 0) && /*#__PURE__*/_react.default.createElement(_popover.EuiPopoverFooter, null, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexGroup, {
    gutterSize: "m",
    justifyContent: "spaceBetween",
    responsive: false
  }, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, {
    grow: false
  }, inactiveSortableColumns.length > 0 && /*#__PURE__*/_react.default.createElement(_popover.EuiPopover, {
    "data-test-subj": "dataGridColumnSortingPopoverColumnSelection",
    isOpen: avilableColumnsisOpen,
    closePopover: function closePopover() {
      return setAvailableColumnsIsOpen(false);
    },
    anchorPosition: "downLeft",
    panelPaddingSize: "none",
    button: /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
      size: "xs",
      flush: "left",
      iconType: "arrowDown",
      iconSide: "right",
      onClick: function onClick() {
        return setAvailableColumnsIsOpen(!avilableColumnsisOpen);
      }
    }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
      token: "euiColumnSorting.pickFields",
      default: "Pick fields to sort by"
    }))
  }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiColumnSorting.sortFieldAriaLabel",
    default: "Sort by: "
  }, function (sortFieldAriaLabel) {
    return /*#__PURE__*/_react.default.createElement("div", {
      className: "euiDataGridColumnSorting__fieldList",
      role: "listbox"
    }, inactiveSortableColumns.map(function (_ref8) {
      var id = _ref8.id,
        defaultSortDirection = _ref8.defaultSortDirection;
      return /*#__PURE__*/_react.default.createElement("button", {
        key: id,
        className: "euiDataGridColumnSorting__field",
        "aria-label": "".concat(sortFieldAriaLabel, " ").concat(id),
        role: "option",
        "aria-selected": "false",
        "data-test-subj": "dataGridColumnSortingPopoverColumnSelection-".concat(id),
        onClick: function onClick() {
          var nextColumns = _toConsumableArray(sorting.columns);
          nextColumns.push({
            id: id,
            direction: defaultSortDirection || schemaDetails(id) && schemaDetails(id).defaultSortDirection || 'asc'
          });
          sorting.onSort(nextColumns);
        }
      }, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexGroup, {
        alignItems: "center",
        gutterSize: "s",
        component: "span",
        responsive: false
      }, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_token.EuiToken, {
        iconType: schemaDetails(id) != null ? (0, _data_grid_schema.getDetailsForSchema)(schemaDetectors, schema[id].columnType).icon : 'tokenString',
        color: schemaDetails(id) != null ? (0, _data_grid_schema.getDetailsForSchema)(schemaDetectors, schema[id].columnType).color : undefined
      })), /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_text.EuiText, {
        size: "xs"
      }, displayValues[id]))));
    }));
  }))), sorting.columns.length > 0 ? /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
    size: "xs",
    flush: "right",
    onClick: function onClick() {
      return sorting.onSort([]);
    }
  }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiColumnSorting.clearAll",
    default: "Clear sorting"
  }))) : null)));
  return columnSorting;
};
exports.useDataGridColumnSorting = useDataGridColumnSorting;