function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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 _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 _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 _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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

/*
 * 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 from 'react';
import PropTypes from "prop-types";
import { OuiI18n } from '../i18n';
import { OuiDraggable } from '../drag_and_drop';
import { OuiScreenReaderOnly } from '../accessibility';
import { OuiFlexGroup, OuiFlexItem } from '../flex';
import { OuiButtonIcon, OuiButtonGroup } from '../button';
import { OuiIcon } from '../icon';
import { OuiText } from '../text';
import { getDetailsForSchema } from './data_grid_schema';
import { OuiToken } from '../token';
export var defaultSortAscLabel = /*#__PURE__*/React.createElement(OuiI18n, {
  token: "ouiColumnSortingDraggable.defaultSortAsc",
  default: "A-Z"
});
export var defaultSortDescLabel = /*#__PURE__*/React.createElement(OuiI18n, {
  token: "ouiColumnSortingDraggable.defaultSortDesc",
  default: "Z-A"
});
export var OuiDataGridColumnSortingDraggable = function OuiDataGridColumnSortingDraggable(_ref) {
  var id = _ref.id,
      display = _ref.display,
      direction = _ref.direction,
      index = _ref.index,
      sorting = _ref.sorting,
      schema = _ref.schema,
      schemaDetectors = _ref.schemaDetectors,
      rest = _objectWithoutProperties(_ref, ["id", "display", "direction", "index", "sorting", "schema", "schemaDetectors"]);

  var schemaDetails = schema.hasOwnProperty(id) && schema[id].columnType != null ? getDetailsForSchema(schemaDetectors, schema[id].columnType) : null;
  var textSortAsc = schemaDetails != null ? schemaDetails.sortTextAsc : defaultSortAscLabel;
  var textSortDesc = schemaDetails != null ? schemaDetails.sortTextDesc : defaultSortDescLabel;
  var toggleOptions = [{
    id: "".concat(id, "Asc"),
    value: 'asc',
    label: textSortAsc,
    'data-test-subj': "ouiDataGridColumnSorting-sortColumn-".concat(id, "-asc")
  }, {
    id: "".concat(id, "Desc"),
    value: 'desc',
    label: textSortDesc,
    'data-test-subj': "ouiDataGridColumnSorting-sortColumn-".concat(id, "-desc")
  }];
  return /*#__PURE__*/React.createElement(OuiDraggable, _extends({
    draggableId: id,
    index: index
  }, rest), function (provided, state) {
    return /*#__PURE__*/React.createElement("div", {
      className: "ouiDataGridColumnSorting__item ".concat(state.isDragging && 'ouiDataGridColumnSorting__item-isDragging')
    }, /*#__PURE__*/React.createElement(OuiScreenReaderOnly, null, /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement(OuiI18n, {
      token: "ouiColumnSortingDraggable.activeSortLabel",
      default: "is sorting this data grid"
    }, function (activeSortLabel) {
      return /*#__PURE__*/React.createElement("span", null, display, " ", activeSortLabel);
    }))), /*#__PURE__*/React.createElement(OuiFlexGroup, {
      gutterSize: "xs",
      alignItems: "center",
      responsive: false,
      "data-test-subj": "ouiDataGridColumnSorting-sortColumn-".concat(id)
    }, /*#__PURE__*/React.createElement(OuiFlexItem, {
      grow: false
    }, /*#__PURE__*/React.createElement(OuiI18n, {
      token: "ouiColumnSortingDraggable.removeSortLabel",
      default: "Remove from data grid sort:"
    }, function (removeSortLabel) {
      return /*#__PURE__*/React.createElement(OuiButtonIcon, {
        color: "text",
        className: "ouiDataGridColumnSorting__button",
        "aria-label": "".concat(removeSortLabel, " ").concat(id),
        iconType: "cross",
        onClick: function onClick() {
          var nextColumns = _toConsumableArray(sorting.columns);

          var columnIndex = nextColumns.map(function (_ref2) {
            var id = _ref2.id;
            return id;
          }).indexOf(id);
          nextColumns.splice(columnIndex, 1);
          sorting.onSort(nextColumns);
        }
      });
    })), /*#__PURE__*/React.createElement(OuiFlexItem, {
      grow: false
    }, /*#__PURE__*/React.createElement(OuiToken, {
      color: schemaDetails != null ? schemaDetails.color : undefined,
      iconType: schemaDetails != null ? schemaDetails.icon : 'tokenString'
    })), /*#__PURE__*/React.createElement(OuiFlexItem, {
      "aria-hidden": true
    }, /*#__PURE__*/React.createElement(OuiText, {
      size: "xs"
    }, /*#__PURE__*/React.createElement("p", null, display))), /*#__PURE__*/React.createElement(OuiFlexItem, {
      className: "ouiDataGridColumnSorting__orderButtons"
    }, /*#__PURE__*/React.createElement(OuiI18n, {
      token: "ouiColumnSortingDraggable.toggleLegend",
      default: "Select sorting method for field: "
    }, function (toggleLegend) {
      return /*#__PURE__*/React.createElement(OuiButtonGroup, {
        legend: "".concat(toggleLegend, " ").concat(id),
        name: id,
        isFullWidth: true,
        options: toggleOptions,
        "data-test-subj": "-".concat(direction),
        buttonSize: "compressed",
        className: "ouiDataGridColumnSorting__order",
        idSelected: direction === 'asc' ? "".concat(id, "Asc") : "".concat(id, "Desc"),
        onChange: function onChange(_, direction) {
          var nextColumns = _toConsumableArray(sorting.columns);

          var columnIndex = nextColumns.map(function (_ref3) {
            var id = _ref3.id;
            return id;
          }).indexOf(id);
          nextColumns.splice(columnIndex, 1, {
            id: id,
            direction: direction
          });
          sorting.onSort(nextColumns);
        }
      });
    })), /*#__PURE__*/React.createElement(OuiFlexItem, _extends({
      grow: false
    }, provided.dragHandleProps), /*#__PURE__*/React.createElement("div", provided.dragHandleProps, /*#__PURE__*/React.createElement(OuiIcon, {
      type: "grab",
      color: "subdued"
    })))));
  });
};
/* OUI -> EUI Aliases: Build-Time */

OuiDataGridColumnSortingDraggable.propTypes = {
  id: PropTypes.string.isRequired,
  direction: PropTypes.string.isRequired,
  index: PropTypes.number.isRequired,
  sorting: PropTypes.shape({
    /**
       * A function that receives updated column sort details in response to user interactions in the toolbar controls
       */
    onSort: PropTypes.func.isRequired,

    /**
       * An array of the column ids currently being sorted and their sort direction. The array order determines the sort order. `{ id: 'A'; direction: 'asc' }`
       */
    columns: PropTypes.arrayOf(PropTypes.shape({
      id: PropTypes.string.isRequired,
      direction: PropTypes.oneOf(["asc", "desc"]).isRequired
    }).isRequired).isRequired
  }).isRequired,
  schema: PropTypes.shape({}).isRequired,
  schemaDetectors: PropTypes.arrayOf(PropTypes.shape({
    /**
       * The name of this data type, matches #OuiDataGridColumn / schema `schema`
       */
    type: PropTypes.string.isRequired,

    /**
       * The function given the text value of a cell and returns a score of [0...1] of how well the value matches this data type
       */
    detector: PropTypes.func.isRequired,

    /**
       * A custom comparator function when performing in-memory sorting on this data type, takes `(a: string, b: string, direction: 'asc' | 'desc) => -1 | 0 | 1`
       */
    comparator: PropTypes.func,

    /**
       * The icon used to visually represent this data type. Accepts any `OuiIcon IconType`.
       */
    icon: PropTypes.oneOfType([PropTypes.oneOf(["accessibility", "addDataApp", "advancedSettingsApp", "aggregate", "alert", "analyzeEvent", "annotation", "anomalyDetection", "apmApp", "apmTrace", "apps", "appSearchApp", "arrowDown", "arrowLeft", "arrowRight", "arrowUp", "asterisk", "auditbeatApp", "beaker", "bell", "bellSlash", "bolt", "boxesHorizontal", "boxesVertical", "branch", "broom", "brush", "bug", "bullseye", "calendar", "canvasApp", "codeApp", "check", "checkInCircleFilled", "cheer", "classificationJob", "clock", "cloudDrizzle", "cloudStormy", "cloudSunny", "color", "compute", "console", "consoleApp", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crosshairs", "crossInACircleFilled", "currency", "cut", "dashboardApp", "database", "dataVisualizer", "devToolsApp", "discoverApp", "document", "documentation", "documentEdit", "documents", "dot", "download", "editorAlignCenter", "editorAlignLeft", "editorAlignRight", "editorBold", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "editorItalic", "editorItemAlignLeft", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "editorStrike", "editorTable", "editorUnderline", "editorUndo", "editorUnorderedList", "email", "empty", "emsApp", "eql", "eraser", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "filebeatApp", "filter", "flag", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "iInCircle", "image", "importAction", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "inputOutput", "inspect", "invert", "ip", "keyboardShortcut", "kqlField", "kqlFunction", "kqlOperand", "kqlSelector", "kqlValue", "layers", "lensApp", "link", "list", "listAdd", "lock", "lockOpen", "logsApp", "logoAerospike", "logoApache", "logoAppSearch", "logoAWS", "logoAWSMono", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticsearch", "logoElasticStack", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOpenSearch", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "machineLearningApp", "magnet", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "mapMarker", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusInCircle", "minusInCircleFilled", "mobile", "monitoringApp", "moon", "nested", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "partial", "paperClip", "pause", "pencil", "percent", "pin", "pinFilled", "pipelineApp", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "polygon", "popout", "push", "questionInCircle", "quote", "radius", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "shard", "share", "snowflake", "sortable", "sortDown", "sortLeft", "sortRight", "sortUp", "spacesApp", "sqlApp", "starEmpty", "starEmptySpace", "starFilled", "starFilledSpace", "starMinusEmpty", "starMinusFilled", "starPlusEmpty", "starPlusFilled", "stats", "stop", "stopFilled", "stopSlash", "storage", "string", "submodule", "swatchInput", "symlink", "tableOfContents", "tableDensityExpanded", "tableDensityCompact", "tableDensityNormal", "tag", "tear", "temperature", "timeline", "timelionApp", "timeslider", "training", "trash", "upgradeAssistantApp", "uptimeApp", "unfold", "unlink", "user", "users", "usersRolesApp", "vector", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visBuilder", "visBuilderSavedObject", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "visPie", "visQueryDQL", "visQueryPPL", "visQueryPromQL", "visQuerySQL", "visTable", "visTagCloud", "visText", "visTimelion", "visualizeApp", "visVega", "visVisualBuilder", "watchesApp", "wordWrap", "wordWrapDisabled", "workplaceSearchApp", "wrench", "tokenClass", "tokenProperty", "tokenEnum", "tokenVariable", "tokenMethod", "tokenAnnotation", "tokenException", "tokenInterface", "tokenParameter", "tokenField", "tokenElement", "tokenFunction", "tokenBoolean", "tokenString", "tokenArray", "tokenNumber", "tokenConstant", "tokenObject", "tokenEvent", "tokenKey", "tokenNull", "tokenStruct", "tokenPackage", "tokenOperator", "tokenEnumMember", "tokenRepo", "tokenSymbol", "tokenFile", "tokenModule", "tokenNamespace", "tokenDate", "tokenIP", "tokenNested", "tokenAlias", "tokenShape", "tokenGeo", "tokenRange", "tokenBinary", "tokenJoin", "tokenPercolator", "tokenFlattened", "tokenRankFeature", "tokenRankFeatures", "tokenKeyword", "tokenCompletionSuggester", "tokenDenseVector", "tokenText", "tokenTokenCount", "tokenSearchType", "tokenHistogram"]).isRequired, PropTypes.string.isRequired, PropTypes.elementType.isRequired]).isRequired,

    /**
       * The color associated with this data type; it's used to color the icon token
       */
    color: PropTypes.oneOfType([PropTypes.oneOfType([PropTypes.oneOf(["ouiColorVis0", "ouiColorVis1", "ouiColorVis2", "ouiColorVis3", "ouiColorVis4", "ouiColorVis5", "ouiColorVis6", "ouiColorVis7", "ouiColorVis8", "ouiColorVis9", "gray"]).isRequired, PropTypes.string.isRequired]).isRequired, PropTypes.string.isRequired]),

    /**
       * Text for how to represent an ascending sort of this data type, e.g. 'A -> Z'
       */
    sortTextAsc: PropTypes.node.isRequired,

    /**
       * Text for how to represent a descending sort of this data type, e.g. 'Z -> A'
       */
    sortTextDesc: PropTypes.node.isRequired,

    /**
       * Whether this column is sortable (defaults to true)
       */
    isSortable: PropTypes.bool,

    /**
       *  This property controls the capitalization of text
       */
    textTransform: PropTypes.oneOf(["uppercase", "lowercase", "capitalize"]),

    /**
       * Default sort direction of the column
       */
    defaultSortDirection: PropTypes.oneOf(["asc", "desc"])
  }).isRequired).isRequired,

  /**
     * Value to be shown in column sorting popover.
     */
  display: PropTypes.string.isRequired
};

/* OUI -> EUI Aliases: Build-Time */
export { EuiDataGridColumnSortingDraggable } from '../../eui_components/datagrid/column_sorting_draggable';