var _excluded = ["onChange"],
  _excluded2 = ["onChange"];
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
/*
 * 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.
 */

import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import isEqual from 'lodash/isEqual';
import { logicalStyle, mathWithUnits } from '../../../global_styling';
import { useUpdateEffect, useDeepEqual, useEuiTheme } from '../../../services';
import { EuiI18n, useEuiI18n } from '../../i18n';
import { EuiPopover, EuiPopoverFooter } from '../../popover';
import { EuiButtonIcon, EuiButtonGroup, EuiButtonEmpty } from '../../button';
import { EuiFormRow, EuiFieldNumber } from '../../form';
import { euiFormMaxWidth } from '../../form/form.styles';
import { EuiFlexGroup } from '../../flex';
import { EuiToolTip } from '../../tool_tip';
import { getNestedObjectOptions } from './data_grid_toolbar';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var startingStyles = {
  cellPadding: 'm',
  fontSize: 'm',
  border: 'all',
  stripes: false,
  rowHover: 'highlight',
  header: 'shade',
  footer: 'overline',
  stickyFooter: true
};
var emptyRowHeightsOptions = {};

/**
 * Cell density
 */

var densityOptions = ['compact', 'normal', 'expanded'];
var densityStyles = {
  expanded: {
    fontSize: 'l',
    cellPadding: 'l'
  },
  normal: {
    fontSize: 'm',
    cellPadding: 'm'
  },
  compact: {
    fontSize: 's',
    cellPadding: 's'
  }
};
var convertGridStylesToSelection = function convertGridStylesToSelection(gridStyles) {
  if (gridStyles.fontSize === 's' && gridStyles.cellPadding === 's') return 'compact';
  if (gridStyles.fontSize === 'm' && gridStyles.cellPadding === 'm') return 'normal';
  if (gridStyles.fontSize === 'l' && gridStyles.cellPadding === 'l') return 'expanded';
  return '';
};
var DensityControl = function DensityControl(_ref) {
  var gridStyles = _ref.gridStyles,
    onChange = _ref.onChange;
  var getDensity = useMemo(function () {
    return convertGridStylesToSelection(gridStyles);
  }, [gridStyles]);
  var setDensity = useCallback(function (density) {
    onChange(densityStyles[density]);
  }, [onChange]);
  return ___EmotionJSX(EuiI18n, {
    tokens: ['euiDisplaySelector.densityLabel', 'euiDisplaySelector.labelCompact', 'euiDisplaySelector.labelNormal', 'euiDisplaySelector.labelExpanded'],
    defaults: ['Density', 'Compact', 'Normal', 'Expanded']
  }, function (_ref2) {
    var _ref3 = _slicedToArray(_ref2, 4),
      densityLabel = _ref3[0],
      labelCompact = _ref3[1],
      labelNormal = _ref3[2],
      labelExpanded = _ref3[3];
    return ___EmotionJSX(EuiFormRow, {
      label: densityLabel,
      display: "columnCompressed"
    }, ___EmotionJSX(EuiButtonGroup, {
      legend: densityLabel,
      buttonSize: "compressed",
      isFullWidth: true,
      options: [{
        id: densityOptions[0],
        label: labelCompact
      }, {
        id: densityOptions[1],
        label: labelNormal
      }, {
        id: densityOptions[2],
        label: labelExpanded
      }],
      onChange: setDensity,
      idSelected: getDensity,
      "data-test-subj": "densityButtonGroup"
    }));
  });
};

/**
 * Row heights
 */

var rowHeightSelectionOptions = ['auto', 'static'];
var convertRowHeightsOptionsToSelection = function convertRowHeightsOptionsToSelection(rowHeightsOptions) {
  var defaultHeight = rowHeightsOptions.defaultHeight;

  // Custom pixel row height values don't have a corresponding UI element
  if (typeof defaultHeight === 'number' || _typeof(defaultHeight) === 'object' && defaultHeight.height) {
    return '';
  }
  if (defaultHeight === 'auto') {
    return rowHeightSelectionOptions[0];
  }
  return rowHeightSelectionOptions[1];
};
var _ref7 = process.env.NODE_ENV === "production" ? {
  name: "ueqtrq-RowHeightControl",
  styles: "flex-shrink:0;flex-basis:66.6%;label:RowHeightControl;"
} : {
  name: "ueqtrq-RowHeightControl",
  styles: "flex-shrink:0;flex-basis:66.6%;label:RowHeightControl;",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
};
var RowHeightControl = function RowHeightControl(_ref4) {
  var rowHeightsOptions = _ref4.rowHeightsOptions,
    onChange = _ref4.onChange;
  var autoBelowLineCount = rowHeightsOptions.autoBelowLineCount;
  var _useState = useState(1),
    _useState2 = _slicedToArray(_useState, 2),
    lineCountInput = _useState2[0],
    setLineCountInput = _useState2[1];
  var setLineCountHeight = useCallback(function (event) {
    var newLineCount = Number(event.currentTarget.value);
    setLineCountInput(newLineCount);
    onChange({
      rowHeights: {},
      // Unset all row-specific line counts
      defaultHeight: newLineCount > 1 ? {
        lineCount: newLineCount
      } : undefined // lineCount: 1 is the same as undefined, and this helps correctly display the reset button
    });
  }, [onChange]);
  useEffect(function () {
    var passedLineCount = _typeof(rowHeightsOptions === null || rowHeightsOptions === void 0 ? void 0 : rowHeightsOptions.defaultHeight) === 'object' ? rowHeightsOptions.defaultHeight.lineCount : undefined;

    // If lineCount updates come in from consumer changes, update the input to reflect that
    if (passedLineCount) {
      setLineCountInput(passedLineCount);
    }
    // If set back to undefined/single line height (typically from the reset button)
    if ((rowHeightsOptions === null || rowHeightsOptions === void 0 ? void 0 : rowHeightsOptions.defaultHeight) === undefined) {
      setLineCountInput(1);
    }
  }, [rowHeightsOptions === null || rowHeightsOptions === void 0 ? void 0 : rowHeightsOptions.defaultHeight]);
  var rowHeightSelection = useMemo(function () {
    return convertRowHeightsOptionsToSelection(rowHeightsOptions);
  }, [rowHeightsOptions]);
  var setRowHeight = useCallback(function (option) {
    var rowHeightsOptions = {
      rowHeights: {} // Unset all row-specific heights
    };
    if (option === rowHeightSelectionOptions[0]) {
      rowHeightsOptions.defaultHeight = 'auto';
    } else if (option === rowHeightSelectionOptions[1]) {
      var lineCount = Number(lineCountInput);
      if (lineCount > 1) {
        rowHeightsOptions.defaultHeight = {
          lineCount: lineCount
        };
      } else {
        // lineCount: 1 is the same as single/undefined
        rowHeightsOptions.defaultHeight = undefined;
      }
    }
    onChange(rowHeightsOptions);
  }, [lineCountInput, onChange]);
  return ___EmotionJSX(EuiI18n, {
    tokens: ['euiDisplaySelector.rowHeightLabel', 'euiDisplaySelector.labelAuto', 'euiDisplaySelector.labelStatic', 'euiDisplaySelector.labelMax'],
    defaults: ['Lines per row', 'Auto', 'Static', 'Max']
  }, function (_ref5) {
    var _ref6 = _slicedToArray(_ref5, 4),
      rowHeightLabel = _ref6[0],
      labelAuto = _ref6[1],
      labelStatic = _ref6[2],
      labelMax = _ref6[3];
    return ___EmotionJSX(EuiFormRow, {
      label: rowHeightLabel,
      display: "columnCompressed"
    }, ___EmotionJSX(EuiFlexGroup, {
      gutterSize: "s",
      responsive: false
    }, ___EmotionJSX(EuiButtonGroup, {
      legend: rowHeightLabel,
      css: _ref7,
      buttonSize: "compressed",
      isFullWidth: true,
      options: [{
        id: rowHeightSelectionOptions[0],
        label: labelAuto
      }, {
        id: rowHeightSelectionOptions[1],
        label: autoBelowLineCount ? labelMax : labelStatic
      }],
      onChange: setRowHeight,
      idSelected: rowHeightSelection,
      "data-test-subj": "rowHeightButtonGroup"
    }), ___EmotionJSX(EuiFieldNumber, {
      "aria-label": rowHeightLabel,
      compressed: true,
      min: 1,
      max: 20,
      disabled: rowHeightSelection !== rowHeightSelectionOptions[1],
      value: lineCountInput,
      onChange: setLineCountHeight,
      "data-test-subj": "lineCountNumber"
    })));
  });
};

/**
 * Display settings/selector popover
 */

export var useDataGridDisplaySelector = function useDataGridDisplaySelector(showDisplaySelector, passedGridStyles) {
  var _showDisplaySelector$;
  var passedRowHeightsOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : emptyRowHeightsOptions;
  /**
   * Grid style changes
   */
  var _useState3 = useState(passedGridStyles),
    _useState4 = _slicedToArray(_useState3, 2),
    gridStyles = _useState4[0],
    setGridStyles = _useState4[1];

  // Update if consumers pass new grid style configurations
  var stablePassedGridStyles = useDeepEqual(passedGridStyles);
  useUpdateEffect(function () {
    setGridStyles(stablePassedGridStyles);
  }, [stablePassedGridStyles]);

  // Update on user display selector change
  var onUserGridStyleChange = useCallback(function (styles) {
    return setGridStyles(function (prevStyles) {
      var changedStyles = _objectSpread(_objectSpread({}, prevStyles), styles);
      var onChange = changedStyles.onChange,
        rest = _objectWithoutProperties(changedStyles, _excluded);
      onChange === null || onChange === void 0 || onChange(rest);
      return changedStyles;
    });
  }, []);
  var densityControl = useMemo(function () {
    var show = getNestedObjectOptions(showDisplaySelector, 'allowDensity');
    return show ? ___EmotionJSX(DensityControl, {
      gridStyles: gridStyles,
      onChange: onUserGridStyleChange
    }) : null;
  }, [showDisplaySelector, gridStyles, onUserGridStyleChange]);

  /**
   * Row height changes
   */
  var _useState5 = useState(passedRowHeightsOptions),
    _useState6 = _slicedToArray(_useState5, 2),
    rowHeightsOptions = _useState6[0],
    setRowHeightsOptions = _useState6[1];

  // Update if consumers pass new row height configurations
  var stablePassedRowHeights = useDeepEqual(passedRowHeightsOptions);
  useUpdateEffect(function () {
    setRowHeightsOptions(stablePassedRowHeights);
  }, [stablePassedRowHeights]);

  // Update on user display selector change
  var onUserRowHeightChange = useCallback(function (options) {
    return setRowHeightsOptions(function (prevOptions) {
      var changedOptions = _objectSpread(_objectSpread({}, prevOptions), options);
      var onChange = changedOptions.onChange,
        rest = _objectWithoutProperties(changedOptions, _excluded2);
      onChange === null || onChange === void 0 || onChange(rest);
      return changedOptions;
    });
  }, []);
  var rowHeightControl = useMemo(function () {
    var show = getNestedObjectOptions(showDisplaySelector, 'allowRowHeight');
    return show ? ___EmotionJSX(RowHeightControl, {
      rowHeightsOptions: rowHeightsOptions,
      onChange: onUserRowHeightChange
    }) : null;
  }, [showDisplaySelector, rowHeightsOptions, onUserRowHeightChange]);

  /**
   * Reset button
   */
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    showResetButton = _useState8[0],
    setShowResetButton = _useState8[1];
  var initialGridStyles = useRef(passedGridStyles);
  var initialRowHeightsOptions = useRef(passedRowHeightsOptions);
  var resetToInitialState = useCallback(function () {
    setGridStyles(initialGridStyles.current);
    setRowHeightsOptions(initialRowHeightsOptions.current);
  }, []);
  useUpdateEffect(function () {
    setShowResetButton(!isEqual(rowHeightsOptions.defaultHeight, initialRowHeightsOptions.current.defaultHeight) || gridStyles.fontSize !== initialGridStyles.current.fontSize || gridStyles.cellPadding !== initialGridStyles.current.cellPadding);
  }, [rowHeightsOptions.defaultHeight, gridStyles.fontSize, gridStyles.cellPadding]);
  var resetButton = useMemo(function () {
    var allowed = getNestedObjectOptions(showDisplaySelector, 'allowResetButton');
    if (!allowed || !showResetButton) return null;
    return ___EmotionJSX(ResetButton, {
      onClick: resetToInitialState
    });
  }, [showDisplaySelector, showResetButton, resetToInitialState]);

  /**
   * Display settings popover
   */
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    isOpen = _useState10[0],
    setIsOpen = _useState10[1];
  var buttonLabel = useEuiI18n('euiDisplaySelector.buttonText', 'Display options');
  var additionalDisplaySettings = typeof showDisplaySelector === 'boolean' ? null : (_showDisplaySelector$ = showDisplaySelector === null || showDisplaySelector === void 0 ? void 0 : showDisplaySelector.additionalDisplaySettings) !== null && _showDisplaySelector$ !== void 0 ? _showDisplaySelector$ : null;
  var customRender = typeof showDisplaySelector === 'boolean' ? undefined : showDisplaySelector === null || showDisplaySelector === void 0 ? void 0 : showDisplaySelector.customRender;
  var euiTheme = useEuiTheme();
  var displaySelector = useMemo(function () {
    var paddingSize = 's';
    var formMaxWidth = euiFormMaxWidth(euiTheme);
    var popoverWidth = mathWithUnits([formMaxWidth, euiTheme.euiTheme.size[paddingSize]], function (x, y) {
      return x + y * 2;
    });
    return densityControl || rowHeightControl || additionalDisplaySettings ? ___EmotionJSX(EuiPopover, {
      "data-test-subj": "dataGridDisplaySelectorPopover",
      isOpen: isOpen,
      closePopover: function closePopover() {
        return setIsOpen(false);
      },
      anchorPosition: "downRight",
      panelPaddingSize: paddingSize,
      panelProps: {
        css: logicalStyle('width', popoverWidth)
      },
      panelClassName: "euiDataGrid__displayPopoverPanel",
      button: ___EmotionJSX(EuiToolTip, {
        content: buttonLabel
      }, ___EmotionJSX(EuiButtonIcon, {
        size: "xs",
        iconType: "controls",
        color: "text",
        "data-test-subj": "dataGridDisplaySelectorButton",
        onClick: function onClick() {
          return setIsOpen(!isOpen);
        },
        "aria-label": buttonLabel
      }))
    }, customRender ? customRender({
      densityControl: densityControl,
      rowHeightControl: rowHeightControl,
      additionalDisplaySettings: additionalDisplaySettings,
      resetButton: resetButton
    }) : ___EmotionJSX(React.Fragment, null, densityControl, rowHeightControl, additionalDisplaySettings, resetButton)) : null;
  }, [euiTheme, densityControl, rowHeightControl, additionalDisplaySettings, resetButton, customRender, buttonLabel, isOpen]);
  return [displaySelector, gridStyles, rowHeightsOptions];
};
var ResetButton = function ResetButton(_ref8) {
  var onClick = _ref8.onClick;
  var resetButtonLabel = useEuiI18n('euiDisplaySelector.resetButtonText', 'Reset to default');
  return ___EmotionJSX(EuiPopoverFooter, null, ___EmotionJSX(EuiFlexGroup, {
    justifyContent: "flexEnd",
    responsive: false
  }, ___EmotionJSX(EuiButtonEmpty, {
    flush: "both",
    size: "xs",
    onClick: onClick,
    "data-test-subj": "resetDisplaySelector"
  }, resetButtonLabel)));
};