function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

/*
 * 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];
};