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.
 */

import React, { Fragment, useState, useMemo, useCallback } from 'react';
import classNames from 'classnames';
import { OuiPopover, OuiPopoverFooter, OuiPopoverTitle } from '../popover';
import { OuiI18n } from '../i18n';
import { OuiButtonEmpty } from '../button';
import { OuiFlexGroup, OuiFlexItem } from '../flex';
import { OuiSwitch, OuiFieldText } from '../form';
import { OuiDragDropContext, OuiDraggable, OuiDroppable, ouiDragDropReorder } from '../drag_and_drop';
import { OuiIcon } from '../icon';
import { useDependentState } from '../../services';
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;
};
export var useDataGridColumnSelector = function useDataGridColumnSelector(availableColumns, columnVisibility, showColumnSelector, displayValues) {
  var allowColumnHiding = getShowColumnSelectorValue(showColumnSelector, 'allowHide');
  var allowColumnReorder = getShowColumnSelectorValue(showColumnSelector, 'allowReorder');
  var _useDependentState = 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 = useMemo(function () {
    return new Set(visibleColumns);
  }, [visibleColumns]);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var setColumns = 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 = ouiDragDropReorder(sortedColumns, sourceIndex, destinationIndex);
    setColumns(nextSortedColumns);
  }
  var numberOfHiddenFields = availableColumns.length - visibleColumns.length;
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    columnSearchText = _useState4[0],
    setColumnSearchText = _useState4[1];
  var controlBtnClasses = classNames('ouiDataGrid__controlBtn', {
    'ouiDataGrid__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.createElement(OuiI18n, {
    token: "ouiColumnSelector.button",
    default: "Columns"
  });
  if (numberOfHiddenFields === 1) {
    buttonText = /*#__PURE__*/React.createElement(OuiI18n, {
      token: "ouiColumnSelector.buttonActiveSingular",
      default: "{numberOfHiddenFields} column hidden",
      values: {
        numberOfHiddenFields: numberOfHiddenFields
      }
    });
  } else if (numberOfHiddenFields > 1) {
    buttonText = /*#__PURE__*/React.createElement(OuiI18n, {
      token: "ouiColumnSelector.buttonActivePlural",
      default: "{numberOfHiddenFields} columns hidden",
      values: {
        numberOfHiddenFields: numberOfHiddenFields
      }
    });
  }
  var columnSelector = /*#__PURE__*/React.createElement(OuiPopover, {
    "data-test-subj": "dataGridColumnSelectorPopover",
    isOpen: isOpen,
    closePopover: function closePopover() {
      return setIsOpen(false);
    },
    anchorPosition: "downLeft",
    panelPaddingSize: "s",
    panelClassName: "ouiDataGridColumnSelectorPopover",
    button: /*#__PURE__*/React.createElement(OuiButtonEmpty, {
      size: "xs",
      iconType: allowColumnHiding ? 'listAdd' : 'list',
      color: "text",
      className: controlBtnClasses,
      "data-test-subj": "dataGridColumnSelectorButton",
      onClick: function onClick() {
        return setIsOpen(!isOpen);
      }
    }, buttonText)
  }, /*#__PURE__*/React.createElement("div", null, allowColumnHiding && /*#__PURE__*/React.createElement(OuiPopoverTitle, null, /*#__PURE__*/React.createElement(OuiI18n, {
    tokens: ['ouiColumnSelector.search', 'ouiColumnSelector.searchcolumns'],
    defaults: ['Search', 'Search columns']
  }, function (_ref3) {
    var _ref4 = _slicedToArray(_ref3, 2),
      search = _ref4[0],
      searchcolumns = _ref4[1];
    return /*#__PURE__*/React.createElement(OuiFieldText, {
      compressed: true,
      placeholder: search,
      "aria-label": searchcolumns,
      value: columnSearchText,
      onChange: function onChange(e) {
        return setColumnSearchText(e.currentTarget.value);
      }
    });
  })), /*#__PURE__*/React.createElement("div", {
    className: "ouiDataGrid__controlScroll"
  }, /*#__PURE__*/React.createElement(OuiDragDropContext, {
    onDragEnd: onDragEnd
  }, /*#__PURE__*/React.createElement(OuiDroppable, {
    droppableId: "columnOrder",
    isDropDisabled: !isDragEnabled
  }, /*#__PURE__*/React.createElement(Fragment, null, filteredColumns.map(function (id, index) {
    return /*#__PURE__*/React.createElement(OuiDraggable, {
      key: id,
      draggableId: id,
      index: index,
      isDragDisabled: !isDragEnabled
    }, function (provided, state) {
      return /*#__PURE__*/React.createElement("div", {
        className: "ouiDataGridColumnSelector__item ".concat(state.isDragging && 'ouiDataGridColumnSelector__item-isDragging')
      }, /*#__PURE__*/React.createElement(OuiFlexGroup, {
        responsive: false,
        gutterSize: "m",
        alignItems: "center"
      }, /*#__PURE__*/React.createElement(OuiFlexItem, null, allowColumnHiding ? /*#__PURE__*/React.createElement(OuiSwitch, {
        name: id,
        label: displayValues[id] || id,
        checked: visibleColumnIds.has(id),
        compressed: true,
        className: "ouiSwitch--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.createElement("span", {
        className: "ouiDataGridColumnSelector__itemLabel"
      }, id)), isDragEnabled && /*#__PURE__*/React.createElement(OuiFlexItem, {
        grow: false
      }, /*#__PURE__*/React.createElement(OuiIcon, {
        type: "grab",
        color: "subdued"
      }))));
    });
  })))))), allowColumnHiding && /*#__PURE__*/React.createElement(OuiPopoverFooter, null, /*#__PURE__*/React.createElement(OuiFlexGroup, {
    gutterSize: "s",
    responsive: false,
    justifyContent: "spaceBetween"
  }, /*#__PURE__*/React.createElement(OuiFlexItem, {
    grow: false
  }, /*#__PURE__*/React.createElement(OuiButtonEmpty, {
    size: "xs",
    flush: "left",
    onClick: function onClick() {
      return setVisibleColumns(sortedColumns);
    }
  }, /*#__PURE__*/React.createElement(OuiI18n, {
    token: "ouiColumnSelector.selectAll",
    default: "Show all"
  }))), /*#__PURE__*/React.createElement(OuiFlexItem, {
    grow: false
  }, /*#__PURE__*/React.createElement(OuiButtonEmpty, {
    size: "xs",
    flush: "right",
    onClick: function onClick() {
      return setVisibleColumns([]);
    }
  }, /*#__PURE__*/React.createElement(OuiI18n, {
    token: "ouiColumnSelector.hideAll",
    default: "Hide all"
  }))))));
  var orderedVisibleColumns = 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 = 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];
};