"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useDataGridColumnSelector = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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");

/*
 * 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 = (0, _slicedToArray2.default)(_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 = (0, _slicedToArray2.default)(_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.ouiDragDropReorder)(sortedColumns, sourceIndex, destinationIndex);
    setColumns(nextSortedColumns);
  }

  var numberOfHiddenFields = availableColumns.length - visibleColumns.length;

  var _useState3 = (0, _react.useState)(''),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      columnSearchText = _useState4[0],
      setColumnSearchText = _useState4[1];

  var controlBtnClasses = (0, _classnames.default)('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.default.createElement(_i18n.OuiI18n, {
    token: "ouiColumnSelector.button",
    default: "Columns"
  });

  if (numberOfHiddenFields === 1) {
    buttonText = /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
      token: "ouiColumnSelector.buttonActiveSingular",
      default: "{numberOfHiddenFields} column hidden",
      values: {
        numberOfHiddenFields: numberOfHiddenFields
      }
    });
  } else if (numberOfHiddenFields > 1) {
    buttonText = /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
      token: "ouiColumnSelector.buttonActivePlural",
      default: "{numberOfHiddenFields} columns hidden",
      values: {
        numberOfHiddenFields: numberOfHiddenFields
      }
    });
  }

  var columnSelector = /*#__PURE__*/_react.default.createElement(_popover.OuiPopover, {
    "data-test-subj": "dataGridColumnSelectorPopover",
    isOpen: isOpen,
    closePopover: function closePopover() {
      return setIsOpen(false);
    },
    anchorPosition: "downLeft",
    panelPaddingSize: "s",
    panelClassName: "ouiDataGridColumnSelectorPopover",
    button: /*#__PURE__*/_react.default.createElement(_button.OuiButtonEmpty, {
      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.OuiPopoverTitle, null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
    tokens: ['ouiColumnSelector.search', 'ouiColumnSelector.searchcolumns'],
    defaults: ['Search', 'Search columns']
  }, function (_ref3) {
    var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
        search = _ref4[0],
        searchcolumns = _ref4[1];

    return /*#__PURE__*/_react.default.createElement(_form.OuiFieldText, {
      compressed: true,
      placeholder: search,
      "aria-label": searchcolumns,
      value: columnSearchText,
      onChange: function onChange(e) {
        return setColumnSearchText(e.currentTarget.value);
      }
    });
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "ouiDataGrid__controlScroll"
  }, /*#__PURE__*/_react.default.createElement(_drag_and_drop.OuiDragDropContext, {
    onDragEnd: onDragEnd
  }, /*#__PURE__*/_react.default.createElement(_drag_and_drop.OuiDroppable, {
    droppableId: "columnOrder",
    isDropDisabled: !isDragEnabled
  }, /*#__PURE__*/_react.default.createElement(_react.Fragment, null, filteredColumns.map(function (id, index) {
    return /*#__PURE__*/_react.default.createElement(_drag_and_drop.OuiDraggable, {
      key: id,
      draggableId: id,
      index: index,
      isDragDisabled: !isDragEnabled
    }, function (provided, state) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: "ouiDataGridColumnSelector__item ".concat(state.isDragging && 'ouiDataGridColumnSelector__item-isDragging')
      }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexGroup, {
        responsive: false,
        gutterSize: "m",
        alignItems: "center"
      }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, null, allowColumnHiding ? /*#__PURE__*/_react.default.createElement(_form.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.default.createElement("span", {
        className: "ouiDataGridColumnSelector__itemLabel"
      }, id)), isDragEnabled && /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_icon.OuiIcon, {
        type: "grab",
        color: "subdued"
      }))));
    });
  })))))), allowColumnHiding && /*#__PURE__*/_react.default.createElement(_popover.OuiPopoverFooter, null, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexGroup, {
    gutterSize: "s",
    responsive: false,
    justifyContent: "spaceBetween"
  }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_button.OuiButtonEmpty, {
    size: "xs",
    flush: "left",
    onClick: function onClick() {
      return setVisibleColumns(sortedColumns);
    }
  }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
    token: "ouiColumnSelector.selectAll",
    default: "Show all"
  }))), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_button.OuiButtonEmpty, {
    size: "xs",
    flush: "right",
    onClick: function onClick() {
      return setVisibleColumns([]);
    }
  }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
    token: "ouiColumnSelector.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 = (0, _toConsumableArray2.default)(sortedColumns);
    nextSortedColumns.splice(moveFromIdx, 1);
    nextSortedColumns.splice(moveToIdx, 0, fromColId);
    setColumns(nextSortedColumns);
  }, [setColumns, sortedColumns]);
  return [columnSelector, orderedVisibleColumns, setVisibleColumns, switchColumnPos];
};

exports.useDataGridColumnSelector = useDataGridColumnSelector;