"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.useDataGridColumnSelector = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _popover = require("../popover");
var _i18n = require("../i18n");
var _button = require("../button");
var _flex = require("../flex");
var _form = require("../form");
var _drag_and_drop = require("../drag_and_drop");
var _icon = require("../icon");
var _services = require("../../services");
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 getShowColumnSelectorValue = function getShowColumnSelectorValue(showColumnSelector, valueName) {
  if (showColumnSelector === false) return false;
  if (showColumnSelector == null) return true;
  if (showColumnSelector === true) return true;
  return showColumnSelector[valueName] !== false;
};
var useDataGridColumnSelector = function useDataGridColumnSelector(availableColumns, columnVisibility, showColumnSelector, displayValues) {
  var allowColumnHiding = getShowColumnSelectorValue(showColumnSelector, 'allowHide');
  var allowColumnReorder = getShowColumnSelectorValue(showColumnSelector, 'allowReorder');
  var _useDependentState = (0, _services.useDependentState)(function () {
      return availableColumns.map(function (_ref) {
        var id = _ref.id;
        return id;
      });
    }, [availableColumns]),
    _useDependentState2 = _slicedToArray(_useDependentState, 2),
    sortedColumns = _useDependentState2[0],
    setSortedColumns = _useDependentState2[1];
  var visibleColumns = columnVisibility.visibleColumns,
    setVisibleColumns = columnVisibility.setVisibleColumns;
  var visibleColumnIds = (0, _react.useMemo)(function () {
    return new Set(visibleColumns);
  }, [visibleColumns]);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var setColumns = (0, _react.useCallback)(function (nextColumns) {
    setSortedColumns(nextColumns);
    var nextVisibleColumns = nextColumns.filter(function (id) {
      return visibleColumnIds.has(id);
    });
    setVisibleColumns(nextVisibleColumns);
  }, [setSortedColumns, setVisibleColumns, visibleColumnIds]);
  function onDragEnd(_ref2) {
    var sourceIndex = _ref2.source.index,
      destination = _ref2.destination;
    var destinationIndex = destination.index;
    var nextSortedColumns = (0, _drag_and_drop.euiDragDropReorder)(sortedColumns, sourceIndex, destinationIndex);
    setColumns(nextSortedColumns);
  }
  var numberOfHiddenFields = availableColumns.length - visibleColumns.length;
  var _useState3 = (0, _react.useState)(''),
    _useState4 = _slicedToArray(_useState3, 2),
    columnSearchText = _useState4[0],
    setColumnSearchText = _useState4[1];
  var controlBtnClasses = (0, _classnames.default)('euiDataGrid__controlBtn', {
    'euiDataGrid__controlBtn--active': numberOfHiddenFields > 0
  });
  var filteredColumns = sortedColumns.filter(function (id) {
    return (displayValues[id] || id).toLowerCase().indexOf(columnSearchText.toLowerCase()) !== -1;
  });
  var isDragEnabled = allowColumnReorder && columnSearchText.length === 0; // only allow drag-and-drop when not filtering columns

  var buttonText = /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiColumnSelector.button",
    default: "Columns"
  });
  if (numberOfHiddenFields === 1) {
    buttonText = /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
      token: "euiColumnSelector.buttonActiveSingular",
      default: "{numberOfHiddenFields} column hidden",
      values: {
        numberOfHiddenFields: numberOfHiddenFields
      }
    });
  } else if (numberOfHiddenFields > 1) {
    buttonText = /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
      token: "euiColumnSelector.buttonActivePlural",
      default: "{numberOfHiddenFields} columns hidden",
      values: {
        numberOfHiddenFields: numberOfHiddenFields
      }
    });
  }
  var columnSelector = /*#__PURE__*/_react.default.createElement(_popover.EuiPopover, {
    "data-test-subj": "dataGridColumnSelectorPopover",
    isOpen: isOpen,
    closePopover: function closePopover() {
      return setIsOpen(false);
    },
    anchorPosition: "downLeft",
    panelPaddingSize: "s",
    panelClassName: "euiDataGridColumnSelectorPopover",
    button: /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
      size: "xs",
      iconType: allowColumnHiding ? 'listAdd' : 'list',
      color: "text",
      className: controlBtnClasses,
      "data-test-subj": "dataGridColumnSelectorButton",
      onClick: function onClick() {
        return setIsOpen(!isOpen);
      }
    }, buttonText)
  }, /*#__PURE__*/_react.default.createElement("div", null, allowColumnHiding && /*#__PURE__*/_react.default.createElement(_popover.EuiPopoverTitle, null, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    tokens: ['euiColumnSelector.search', 'euiColumnSelector.searchcolumns'],
    defaults: ['Search', 'Search columns']
  }, function (_ref3) {
    var _ref4 = _slicedToArray(_ref3, 2),
      search = _ref4[0],
      searchcolumns = _ref4[1];
    return /*#__PURE__*/_react.default.createElement(_form.EuiFieldText, {
      compressed: true,
      placeholder: search,
      "aria-label": searchcolumns,
      value: columnSearchText,
      onChange: function onChange(e) {
        return setColumnSearchText(e.currentTarget.value);
      }
    });
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "euiDataGrid__controlScroll"
  }, /*#__PURE__*/_react.default.createElement(_drag_and_drop.EuiDragDropContext, {
    onDragEnd: onDragEnd
  }, /*#__PURE__*/_react.default.createElement(_drag_and_drop.EuiDroppable, {
    droppableId: "columnOrder",
    isDropDisabled: !isDragEnabled
  }, /*#__PURE__*/_react.default.createElement(_react.Fragment, null, filteredColumns.map(function (id, index) {
    return /*#__PURE__*/_react.default.createElement(_drag_and_drop.EuiDraggable, {
      key: id,
      draggableId: id,
      index: index,
      isDragDisabled: !isDragEnabled
    }, function (provided, state) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: "euiDataGridColumnSelector__item ".concat(state.isDragging && 'euiDataGridColumnSelector__item-isDragging')
      }, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexGroup, {
        responsive: false,
        gutterSize: "m",
        alignItems: "center"
      }, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, null, allowColumnHiding ? /*#__PURE__*/_react.default.createElement(_form.EuiSwitch, {
        name: id,
        label: displayValues[id] || id,
        checked: visibleColumnIds.has(id),
        compressed: true,
        className: "euiSwitch--mini",
        onChange: function onChange(event) {
          var checked = event.target.checked;
          var nextVisibleColumns = sortedColumns.filter(function (columnId) {
            return checked ? visibleColumnIds.has(columnId) || id === columnId : visibleColumnIds.has(columnId) && id !== columnId;
          });
          setVisibleColumns(nextVisibleColumns);
        }
      }) : /*#__PURE__*/_react.default.createElement("span", {
        className: "euiDataGridColumnSelector__itemLabel"
      }, id)), isDragEnabled && /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_icon.EuiIcon, {
        type: "grab",
        color: "subdued"
      }))));
    });
  })))))), allowColumnHiding && /*#__PURE__*/_react.default.createElement(_popover.EuiPopoverFooter, null, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexGroup, {
    gutterSize: "s",
    responsive: false,
    justifyContent: "spaceBetween"
  }, /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
    size: "xs",
    flush: "left",
    onClick: function onClick() {
      return setVisibleColumns(sortedColumns);
    }
  }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiColumnSelector.selectAll",
    default: "Show all"
  }))), /*#__PURE__*/_react.default.createElement(_flex.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
    size: "xs",
    flush: "right",
    onClick: function onClick() {
      return setVisibleColumns([]);
    }
  }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiColumnSelector.hideAll",
    default: "Hide all"
  }))))));
  var orderedVisibleColumns = (0, _react.useMemo)(function () {
    return visibleColumns.map(function (columnId) {
      return availableColumns.find(function (_ref5) {
        var id = _ref5.id;
        return id === columnId;
      });
    } // cast to avoid `undefined`, it filters those out next
    ).filter(function (column) {
      return column != null;
    });
  }, [availableColumns, visibleColumns]);
  /**
   * Used for moving columns left/right, available in the headers actions menu
   */
  var switchColumnPos = (0, _react.useCallback)(function (fromColId, toColId) {
    var moveFromIdx = sortedColumns.indexOf(fromColId);
    var moveToIdx = sortedColumns.indexOf(toColId);
    if (moveFromIdx === -1 || moveToIdx === -1) {
      return;
    }
    var nextSortedColumns = _toConsumableArray(sortedColumns);
    nextSortedColumns.splice(moveFromIdx, 1);
    nextSortedColumns.splice(moveToIdx, 0, fromColId);
    setColumns(nextSortedColumns);
  }, [setColumns, sortedColumns]);
  return [columnSelector, orderedVisibleColumns, setVisibleColumns, switchColumnPos];
};
exports.useDataGridColumnSelector = useDataGridColumnSelector;