"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.defaultSortDescLabel = exports.defaultSortAscLabel = exports.EuiDataGridColumnSortingDraggable = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../../services");
var _accessibility = require("../../accessibility");
var _button = require("../../button");
var _drag_and_drop = require("../../drag_and_drop");
var _flex = require("../../flex");
var _i18n = require("../../i18n");
var _icon = require("../../icon");
var _text = require("../../text");
var _token = require("../../token");
var _data_grid_schema = require("../utils/data_grid_schema");
var _column_sorting = require("./column_sorting.styles");
var _react2 = require("@emotion/react");
var _excluded = ["id", "display", "direction", "index", "sorting", "schema", "schemaDetectors"];
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
var defaultSortAscLabel = exports.defaultSortAscLabel = (0, _react2.jsx)(_i18n.EuiI18n, {
  token: "euiColumnSortingDraggable.defaultSortAsc",
  default: "A-Z"
});
var defaultSortDescLabel = exports.defaultSortDescLabel = (0, _react2.jsx)(_i18n.EuiI18n, {
  token: "euiColumnSortingDraggable.defaultSortDesc",
  default: "Z-A"
});
var EuiDataGridColumnSortingDraggable = exports.EuiDataGridColumnSortingDraggable = function EuiDataGridColumnSortingDraggable(_ref) {
  var id = _ref.id,
    display = _ref.display,
    direction = _ref.direction,
    index = _ref.index,
    sorting = _ref.sorting,
    schema = _ref.schema,
    schemaDetectors = _ref.schemaDetectors,
    rest = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  var schemaDetails = schema.hasOwnProperty(id) && schema[id].columnType != null ? (0, _data_grid_schema.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': "euiDataGridColumnSorting-sortColumn-".concat(id, "-asc")
  }, {
    id: "".concat(id, "Desc"),
    value: 'desc',
    label: textSortDesc,
    'data-test-subj': "euiDataGridColumnSorting-sortColumn-".concat(id, "-desc")
  }];
  var dragHandleAriaLabel = (0, _i18n.useEuiI18n)('euiColumnSortingDraggable.dragHandleAriaLabel', 'Drag handle');
  var removeSort = (0, _react.useCallback)(function () {
    var nextColumns = (0, _toConsumableArray2.default)(sorting.columns);
    var columnIndex = nextColumns.map(function (_ref2) {
      var id = _ref2.id;
      return id;
    }).indexOf(id);
    nextColumns.splice(columnIndex, 1);
    sorting.onSort(nextColumns);
  }, [id, sorting]);
  var toggleLegendHandler = (0, _react.useCallback)(function (_, direction) {
    var nextColumns = (0, _toConsumableArray2.default)(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);
  }, [id, sorting]);
  var styles = (0, _services.useEuiMemoizedStyles)(_column_sorting.euiDataGridColumnSortingStyles);
  return (0, _react2.jsx)(_drag_and_drop.EuiDraggable, (0, _extends2.default)({
    draggableId: id,
    index: index,
    hasInteractiveChildren: true,
    customDragHandle: true,
    usePortal: true
  }, rest), function (provided, state) {
    return (0, _react2.jsx)(_flex.EuiFlexGroup, {
      css: styles.euiDataGridColumnSorting__item,
      className: (0, _classnames.default)('euiDataGridColumnSorting__item', {
        'euiDataGridColumnSorting__item-isDragging': state.isDragging
      }),
      gutterSize: "xs",
      alignItems: "center",
      responsive: false,
      "data-test-subj": "euiDataGridColumnSorting-sortColumn-".concat(id)
    }, (0, _react2.jsx)(_accessibility.EuiScreenReaderOnly, null, (0, _react2.jsx)("p", null, (0, _react2.jsx)(_i18n.EuiI18n, {
      token: "euiColumnSortingDraggable.activeSortLabel",
      default: "{display} is sorting this data grid",
      values: {
        display: display
      }
    }, function (activeSortLabel) {
      return activeSortLabel;
    }))), (0, _react2.jsx)(_flex.EuiFlexItem, {
      grow: false
    }, (0, _react2.jsx)(_i18n.EuiI18n, {
      token: "euiColumnSortingDraggable.removeSortLabel",
      default: "Remove {display} from data grid sort",
      values: {
        display: display
      }
    }, function (removeSortLabel) {
      return (0, _react2.jsx)(_button.EuiButtonIcon, {
        color: "text",
        className: "euiDataGridColumnSorting__button",
        "aria-label": removeSortLabel,
        iconType: "cross",
        onClick: removeSort
      });
    })), (0, _react2.jsx)(_flex.EuiFlexItem
    // This extra column name flex item affords the column more grabbable real estate
    // for mouse users, while hiding repetition for keyboard/screen reader users
    , (0, _extends2.default)({
      css: styles.euiDataGridColumnSorting__name,
      className: "euiDataGridColumnSorting__name"
    }, provided.dragHandleProps, {
      tabIndex: -1,
      "aria-hidden": true
    }), (0, _react2.jsx)(_flex.EuiFlexGroup, {
      gutterSize: "xs",
      alignItems: "center",
      responsive: false
    }, (0, _react2.jsx)(_flex.EuiFlexItem, {
      grow: false
    }, (0, _react2.jsx)(_token.EuiToken, {
      color: schemaDetails != null ? schemaDetails.color : undefined,
      iconType: schemaDetails != null ? schemaDetails.icon : 'tokenString'
    })), (0, _react2.jsx)(_flex.EuiFlexItem, null, (0, _react2.jsx)(_text.EuiText, {
      size: "xs"
    }, display)))), (0, _react2.jsx)(_flex.EuiFlexItem, null, (0, _react2.jsx)(_i18n.EuiI18n, {
      token: "euiColumnSortingDraggable.toggleLegend",
      default: "Select sorting method for {display}",
      values: {
        display: display
      }
    }, function (toggleLegend) {
      return (0, _react2.jsx)(_button.EuiButtonGroup, {
        legend: toggleLegend,
        isFullWidth: true,
        options: toggleOptions,
        buttonSize: "compressed",
        css: styles.euiDataGridColumnSorting__order,
        className: "euiDataGridColumnSorting__order",
        idSelected: direction === 'asc' ? "".concat(id, "Asc") : "".concat(id, "Desc"),
        onChange: toggleLegendHandler
      });
    })), (0, _react2.jsx)(_flex.EuiFlexItem, (0, _extends2.default)({
      grow: false
    }, provided.dragHandleProps, {
      "aria-label": dragHandleAriaLabel
    }), (0, _react2.jsx)(_icon.EuiIcon, {
      type: "dragVertical",
      color: "subdued"
    })));
  });
};
EuiDataGridColumnSortingDraggable.propTypes = {
  id: _propTypes.default.string.isRequired,
  direction: _propTypes.default.string.isRequired,
  index: _propTypes.default.number.isRequired,
  sorting: _propTypes.default.shape({
    /**
       * A function that receives updated column sort details in response to user interactions in the toolbar controls
       */
    onSort: _propTypes.default.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.default.arrayOf(_propTypes.default.shape({
      id: _propTypes.default.string.isRequired,
      direction: _propTypes.default.oneOf(["asc", "desc"]).isRequired
    }).isRequired).isRequired
  }).isRequired,
  schema: _propTypes.default.shape({}).isRequired,
  schemaDetectors: _propTypes.default.arrayOf(_propTypes.default.shape({
    /**
       * The name of this data type, matches {@link EuiDataGridColumn} / `schema`
       */
    type: _propTypes.default.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.default.func.isRequired,
    /**
       * A custom comparator function when performing in-memory sorting on this data type, takes `(a: string, b: string, direction: 'asc' | 'desc', indexes: {aIndex: number, bIndex: number}) => -1 | 0 | 1`
       */
    comparator: _propTypes.default.func,
    /**
       * The icon used to visually represent this data type. Accepts any `EuiIcon IconType`.
       */
    icon: _propTypes.default.oneOfType([_propTypes.default.oneOf(["accessibility", "addDataApp", "addToDashboard", "advancedSettingsApp", "agentApp", "aggregate", "alignBottom", "alignBottomLeft", "alignBottomRight", "alignCenterHorizontal", "alignCenterVertical", "alignLeft", "alignRight", "alignTop", "alignTopLeft", "alignTopRight", "alert", "analyzeEvent", "annotation", "anomalyChart", "chartAnomaly", "anomalySwimLane", "apmApp", "apmTrace", "chartWaterfall", "appSearchApp", "apps", "arrowDown", "chevronSingleDown", "arrowLeft", "chevronSingleLeft", "arrowRight", "chevronSingleRight", "arrowUp", "chevronSingleUp", "arrowStart", "chevronLimitLeft", "arrowEnd", "chevronLimitRight", "article", "asterisk", "at", "archive", "axisX", "axisYLeft", "axisYRight", "auditbeatApp", "backgroundTask", "beaker", "bell", "bellSlash", "beta", "bolt", "boxesHorizontal", "boxesVertical", "branch", "briefcase", "branchUser", "broom", "brush", "bug", "bulb", "bullseye", "calendar", "canvasApp", "casesApp", "changePointDetection", "chartChangePoint", "chartArea", "chartAreaStack", "chartBarHorizontal", "chartBarHorizontalStack", "chartBarVertical", "chartBarVerticalStack", "chartGauge", "chartHeatmap", "chartLine", "chartPie", "chartTagCloud", "chartThreshold", "check", "checkCircle", "checkInCircleFilled", "checkCircleFill", "cheer", "popper", "classificationJob", "clickLeft", "clickRight", "clock", "clockCounter", "clockControl", "cloud", "cloudDrizzle", "cloudStormy", "cloudSunny", "cluster", "code", "codeApp", "color", "paintBucket", "commandLine", "comment", "compare", "compute", "processor", "console", "consoleApp", "container", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "contrast", "contrastHigh", "contrastFill", "controls", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "crossProjectSearch", "createAdvancedJob", "createGenericJob", "createGeoJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crossInCircle", "crossCircle", "crosshair", "crosshairs", "currency", "money", "cut", "scissors", "dashboardApp", "dashedCircle", "dataVisualizer", "database", "desktop", "display", "devToolsApp", "diff", "discoverApp", "distributeHorizontal", "distributeVertical", "download", "drag", "dragHorizontal", "dragVertical", "discuss", "document", "documentEdit", "documentation", "documents", "dot", "dotInCircle", "doubleArrowLeft", "chevronDoubleLeft", "doubleArrowRight", "chevronDoubleRight", "ellipsis", "editorAlignCenter", "textAlignCenter", "editorAlignLeft", "textAlignLeft", "editorAlignRight", "textAlignRight", "editorBold", "textBold", "editorChecklist", "listCheck", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "textHeading", "editorItalic", "textItalic", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignLeft", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "listNumber", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "redo", "editorStrike", "textStrike", "editorTable", "table", "editorUnderline", "textUnderline", "editorUndo", "undo", "editorUnorderedList", "listBullet", "email", "mail", "empty", "emsApp", "endpoint", "eql", "query", "eraser", "error", "errorFilled", "errorFill", "esqlVis", "exit", "logOut", "expand", "maximize", "expandMini", "export", "exportAction", "upload", "external", "eye", "eyeClosed", "eyeSlash", "faceHappy", "faceNeutral", "faceSad", "fieldStatistics", "tableInfo", "filebeatApp", "filter", "filterExclude", "filterIgnore", "filterInclude", "filterInCircle", "flask", "flag", "fleetApp", "fold", "folder", "folderClosed", "folderClose", "folderCheck", "folderExclamation", "folderOpen", "folderOpened", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "grabOmnidirectional", "gradient", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "hourglass", "if", "info", "image", "importAction", "index", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "mapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "indexTemporary", "tableTime", "infinity", "inputOutput", "inspect", "invert", "ip", "key", "keyboard", "kqlField", "queryField", "kqlFunction", "kqlOperand", "queryOperand", "kqlSelector", "querySelector", "kqlValue", "queryValue", "kubernetesNode", "kubernetesPod", "launch", "rocket", "layers", "lensApp", "lettering", "text", "lineBreak", "lineBreakSlash", "lineDash", "lineDashed", "lineDot", "lineDotted", "lineSolid", "link", "linkSlash", "list", "listAdd", "lock", "lockOpen", "logPatternAnalysis", "pattern", "logRateAnalysis", "logoAWS", "logoAWSMono", "logoAerospike", "logoApache", "logoAppSearch", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticStack", "logoElasticsearch", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoVulnerabilityManagement", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logsApp", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "queue", "machineLearningApp", "magnet", "magnify", "magnifyExclamation", "magnifyMinus", "magnifyPlus", "magnifyWithExclamation", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "map", "mapMarker", "waypoint", "megaphone", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusCircle", "minusInCircle", "minusInCircleFilled", "minusInSquare", "minusSquare", "mobile", "monitoringApp", "moon", "move", "namespace", "nested", "newChat", "node", "vectorTriangle", "notebookApp", "number", "offline", "wifiSlash", "online", "wifi", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "palette", "paperClip", "partial", "pause", "payment", "pencil", "percent", "pin", "pinFill", "pinFilled", "pipeBreaks", "pipelineApp", "pipeNoBreaks", "pivot", "play", "playFilled", "plugs", "plus", "plusCircle", "plusInCircle", "plusInCircleFilled", "plusInSquare", "plusSquare", "popout", "presentation", "productRobot", "productAgent", "productCloudInfra", "productDashboard", "productDiscover", "productML", "productStreamsClassic", "productStreamsWired", "push", "send", "question", "quote", "radar", "readOnly", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "return", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "section", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "server", "sessionViewer", "shard", "share", "singleMetricViewer", "snowflake", "sortAscending", "sortDescending", "sortDown", "sortLeft", "sortRight", "sortUp", "sortable", "spaces", "spacesApp", "sparkles", "sqlApp", "star", "starEmpty", "starEmptySpace", "starFill", "starFilled", "starFillSpace", "starFilledSpace", "starMinusEmpty", "starMinusFill", "starMinusFilled", "starPlusEmpty", "starPlusFill", "starPlusFilled", "stats", "stop", "stopFill", "stopFilled", "stopSlash", "storage", "streamsClassic", "streamsWired", "string", "submodule", "sun", "swatchInput", "symlink", "tableDensityCompact", "tableDensityHigh", "tableDensityExpanded", "tableDensityLow", "tableDensityNormal", "tableOfContents", "tag", "tear", "temperature", "thermometer", "thumbDown", "thumbUp", "timeline", "timelineWithArrow", "timelionApp", "timeRefresh", "refreshTime", "timeslider", "training", "transitionBottomIn", "transitionBottomOut", "transitionLeftIn", "transitionLeftOut", "transitionTopIn", "transitionTopOut", "trash", "unfold", "unlink", "upgradeAssistantApp", "uptimeApp", "user", "userAvatar", "users", "usersRolesApp", "unarchive", "vector", "vectorSquare", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "chartMetric", "visPie", "visTable", "visTagCloud", "visText", "visTimelion", "visVega", "visVisualBuilder", "visualizeApp", "vulnerabilityManagementApp", "warning", "warningFilled", "warningFill", "watchesApp", "web", "wordWrap", "wordWrapDisabled", "workflowsApp", "workflow", "workplaceSearchApp", "wrench", "tokenAlias", "tokenAnnotation", "tokenArray", "tokenBinary", "tokenBoolean", "tokenClass", "tokenCompletionSuggester", "tokenConstant", "tokenDate", "tokenDimension", "tokenElement", "tokenEnum", "tokenEnumMember", "tokenEvent", "tokenException", "tokenField", "tokenFile", "tokenFlattened", "tokenFunction", "tokenGeo", "tokenHistogram", "tokenInterface", "tokenIP", "tokenJoin", "tokenKey", "tokenKeyword", "tokenMethod", "tokenMetricCounter", "tokenMetricGauge", "tokenModule", "tokenNamespace", "tokenNested", "tokenNull", "tokenNumber", "tokenObject", "tokenOperator", "tokenPackage", "tokenParameter", "tokenPercolator", "tokenProperty", "tokenRange", "tokenRankFeature", "tokenRankFeatures", "tokenRepo", "tokenSearchType", "tokenSemanticText", "tokenShape", "tokenString", "tokenStruct", "tokenSymbol", "tokenTag", "tokenText", "tokenTokenCount", "tokenVariable", "tokenVectorDense", "tokenDenseVector", "tokenVectorSparse"]).isRequired, _propTypes.default.string.isRequired, _propTypes.default.elementType.isRequired]).isRequired,
    /**
       * The color associated with this data type; it's used to color the icon token
       */
    color: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.any.isRequired, _propTypes.default.string.isRequired]).isRequired, _propTypes.default.string.isRequired]),
    /**
       * Text for how to represent an ascending sort of this data type, e.g. 'A -> Z'
       */
    sortTextAsc: _propTypes.default.node.isRequired,
    /**
       * Text for how to represent a descending sort of this data type, e.g. 'Z -> A'
       */
    sortTextDesc: _propTypes.default.node.isRequired,
    /**
       * Whether columns with this schema are sortable (defaults to true). Can be overridden at the individual {@link EuiDataGridColumn} level
       */
    isSortable: _propTypes.default.bool,
    /**
       * This property controls the capitalization of text
       */
    textTransform: _propTypes.default.oneOf(["uppercase", "lowercase", "capitalize"]),
    /**
       * Default sort direction of columns with this schema. Can be overridden at the individual {@link EuiDataGridColumn} level
       */
    defaultSortDirection: _propTypes.default.oneOf(["asc", "desc"])
  }).isRequired).isRequired,
  /**
     * Value to be shown in column sorting popover.
     */
  display: _propTypes.default.string.isRequired
};