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, useEffect } from 'react';
import classNames from 'classnames';
import { EuiPopover, EuiPopoverFooter } from '../popover';
import { EuiI18n } from '../i18n';
import { EuiText } from '../text';
import { EuiButtonEmpty } from '../button';
import { EuiFlexGroup, EuiFlexItem } from '../flex';
import { EuiDragDropContext, EuiDroppable, euiDragDropReorder } from '../drag_and_drop';
import { EuiDataGridColumnSortingDraggable } from './column_sorting_draggable';
import { getDetailsForSchema } from './data_grid_schema';
import { EuiToken } from '../token';
export var useDataGridColumnSorting = function useDataGridColumnSorting(columns, sorting, schema, schemaDetectors, displayValues) {
  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isOpen = _useState2[0],
      setIsOpen = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      avilableColumnsisOpen = _useState4[0],
      setAvailableColumnsIsOpen = _useState4[1]; // prune any non-existent/hidden columns from sorting


  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 = euiDragDropReorder(sorting.columns, sourceIndex, destinationIndex);
    sorting.onSort(nextColumns);
  }

  var controlBtnClasses = classNames('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 ? 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.createElement(EuiPopover, {
    "data-test-subj": "dataGridColumnSortingPopover",
    isOpen: isOpen,
    closePopover: function closePopover() {
      return setIsOpen(false);
    },
    anchorPosition: "downLeft",
    panelPaddingSize: "s",
    panelClassName: "euiDataGridColumnSortingPopover",
    button: /*#__PURE__*/React.createElement(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.createElement(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.createElement("div", {
    role: "region",
    "aria-live": "assertive",
    className: "euiDataGrid__controlScroll"
  }, /*#__PURE__*/React.createElement(EuiDragDropContext, {
    onDragEnd: onDragEnd
  }, /*#__PURE__*/React.createElement(EuiDroppable, {
    droppableId: "columnSorting"
  }, /*#__PURE__*/React.createElement(Fragment, null, sorting.columns.map(function (_ref7, index) {
    var id = _ref7.id,
        direction = _ref7.direction;
    return /*#__PURE__*/React.createElement(EuiDataGridColumnSortingDraggable, {
      key: id,
      id: id,
      display: displayValues[id],
      direction: direction,
      index: index,
      sorting: sorting,
      schema: schema,
      schemaDetectors: schemaDetectors
    });
  }))))) : /*#__PURE__*/React.createElement(EuiText, {
    size: "s",
    color: "subdued"
  }, /*#__PURE__*/React.createElement("p", {
    role: "alert"
  }, /*#__PURE__*/React.createElement(EuiI18n, {
    token: "euiColumnSorting.emptySorting",
    default: "Currently no fields are sorted"
  }))), (inactiveSortableColumns.length > 0 || sorting.columns.length > 0) && /*#__PURE__*/React.createElement(EuiPopoverFooter, null, /*#__PURE__*/React.createElement(EuiFlexGroup, {
    gutterSize: "m",
    justifyContent: "spaceBetween",
    responsive: false
  }, /*#__PURE__*/React.createElement(EuiFlexItem, {
    grow: false
  }, inactiveSortableColumns.length > 0 && /*#__PURE__*/React.createElement(EuiPopover, {
    "data-test-subj": "dataGridColumnSortingPopoverColumnSelection",
    isOpen: avilableColumnsisOpen,
    closePopover: function closePopover() {
      return setAvailableColumnsIsOpen(false);
    },
    anchorPosition: "downLeft",
    panelPaddingSize: "none",
    button: /*#__PURE__*/React.createElement(EuiButtonEmpty, {
      size: "xs",
      flush: "left",
      iconType: "arrowDown",
      iconSide: "right",
      onClick: function onClick() {
        return setAvailableColumnsIsOpen(!avilableColumnsisOpen);
      }
    }, /*#__PURE__*/React.createElement(EuiI18n, {
      token: "euiColumnSorting.pickFields",
      default: "Pick fields to sort by"
    }))
  }, /*#__PURE__*/React.createElement(EuiI18n, {
    token: "euiColumnSorting.sortFieldAriaLabel",
    default: "Sort by: "
  }, function (sortFieldAriaLabel) {
    return /*#__PURE__*/React.createElement("div", {
      className: "euiDataGridColumnSorting__fieldList",
      role: "listbox"
    }, inactiveSortableColumns.map(function (_ref8) {
      var id = _ref8.id,
          defaultSortDirection = _ref8.defaultSortDirection;
      return /*#__PURE__*/React.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.createElement(EuiFlexGroup, {
        alignItems: "center",
        gutterSize: "s",
        component: "span",
        responsive: false
      }, /*#__PURE__*/React.createElement(EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/React.createElement(EuiToken, {
        iconType: schemaDetails(id) != null ? getDetailsForSchema(schemaDetectors, schema[id].columnType).icon : 'tokenString',
        color: schemaDetails(id) != null ? getDetailsForSchema(schemaDetectors, schema[id].columnType).color : undefined
      })), /*#__PURE__*/React.createElement(EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/React.createElement(EuiText, {
        size: "xs"
      }, displayValues[id]))));
    }));
  }))), sorting.columns.length > 0 ? /*#__PURE__*/React.createElement(EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/React.createElement(EuiButtonEmpty, {
    size: "xs",
    flush: "right",
    onClick: function onClick() {
      return sorting.onSort([]);
    }
  }, /*#__PURE__*/React.createElement(EuiI18n, {
    token: "euiColumnSorting.clearAll",
    default: "Clear sorting"
  }))) : null)));
  return columnSorting;
};