"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FieldFilterPopover = void 0;
var _react = _interopRequireWildcard(require("react"));
var _react2 = require("@emotion/react");
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _field_filter_apply_button = require("./field_filter_apply_button");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

// This component is mostly inspired by EUI's Data Grid Column Selector
// https://github.com/elastic/eui/blob/main/src/components/datagrid/controls/column_selector.tsx
const FieldFilterPopover = ({
  disabled,
  disabledApplyButton,
  uniqueFieldNames,
  onChange
}) => {
  const euiThemeContext = (0, _eui.useEuiTheme)();
  // Inspired by https://github.com/elastic/eui/blob/main/src/components/datagrid/controls/_data_grid_column_selector.scss
  const fieldSelectPopover = (0, _react.useMemo)(() => (0, _react2.css)`
      ${(0, _eui.euiYScrollWithShadows)(euiThemeContext, {})}
      max-height: 400px;
    `, [euiThemeContext]);
  const [isTouched, setIsTouched] = (0, _react.useState)(false);
  const [fieldSearchText, setFieldSearchText] = (0, _react.useState)('');
  const [skippedFields, setSkippedFields] = (0, _react.useState)([]);
  const setFieldsFilter = (fieldNames, checked) => {
    let updatedSkippedFields = [...skippedFields];
    if (!checked) {
      updatedSkippedFields.push(...fieldNames);
    } else {
      updatedSkippedFields = skippedFields.filter(d => !fieldNames.includes(d));
    }
    setSkippedFields(updatedSkippedFields);
    setIsTouched(true);
  };
  const [isFieldSelectionPopoverOpen, setIsFieldSelectionPopoverOpen] = (0, _react.useState)(false);
  const onFieldSelectionButtonClick = () => setIsFieldSelectionPopoverOpen(isOpen => !isOpen);
  const closePopover = () => setIsFieldSelectionPopoverOpen(false);
  const filteredUniqueFieldNames = (0, _react.useMemo)(() => {
    return uniqueFieldNames.filter(d => d.toLowerCase().indexOf(fieldSearchText.toLowerCase()) !== -1);
  }, [fieldSearchText, uniqueFieldNames]);

  // If the supplied list of unique field names changes, do a sanity check to only
  // keep field names in the list of skipped fields that still are in the list of unique fields.
  (0, _react.useEffect)(() => {
    setSkippedFields(previousSkippedFields => previousSkippedFields.filter(d => uniqueFieldNames.includes(d)));
  }, [uniqueFieldNames]);
  const selectedFieldCount = uniqueFieldNames.length - skippedFields.length;
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPopover, {
    "data-test-subj": "aiopsFieldFilterPopover",
    anchorPosition: "downLeft",
    panelPaddingSize: "s",
    button: /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
      "data-test-subj": "aiopsFieldFilterButton",
      onClick: onFieldSelectionButtonClick,
      disabled: disabled,
      size: "s",
      iconType: "arrowDown",
      iconSide: "right",
      iconSize: "s",
      color: "text"
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.aiops.logRateAnalysis.page.fieldFilterButtonLabel",
      defaultMessage: "Filter fields"
    })),
    isOpen: isFieldSelectionPopoverOpen,
    closePopover: closePopover
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiPopoverTitle, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    size: "xs",
    color: "subdued",
    style: {
      maxWidth: '400px'
    }
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.logRateAnalysis.page.fieldFilterHelpText",
    defaultMessage: "Deselect non-relevant fields to remove them from groups and click the Apply button to rerun the grouping.  Use the search bar to filter the list, then select/deselect multiple fields with the actions below."
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
    compressed: true,
    placeholder: _i18n.i18n.translate('xpack.aiops.analysis.fieldSelectorPlaceholder', {
      defaultMessage: 'Search'
    }),
    "aria-label": _i18n.i18n.translate('xpack.aiops.analysis.fieldSelectorAriaLabel', {
      defaultMessage: 'Filter fields'
    }),
    value: fieldSearchText,
    onChange: e => setFieldSearchText(e.currentTarget.value),
    "data-test-subj": "aiopsFieldSelectorSearch"
  })), /*#__PURE__*/_react.default.createElement("div", {
    css: fieldSelectPopover,
    "data-test-subj": "aiopsFieldSelectorFieldNameList"
  }, filteredUniqueFieldNames.map(fieldName => /*#__PURE__*/_react.default.createElement("div", {
    key: fieldName,
    css: {
      padding: '4px'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiSwitch, {
    "data-test-subj": `aiopsFieldSelectorFieldNameListItem${!skippedFields.includes(fieldName) ? ' checked' : ''}`,
    className: "euiSwitch--mini",
    compressed: true,
    label: fieldName,
    onChange: e => setFieldsFilter([fieldName], e.target.checked),
    checked: !skippedFields.includes(fieldName)
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiPopoverFooter, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "s",
    responsive: false,
    justifyContent: "spaceBetween",
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    size: "xs",
    flush: "left",
    onClick: () => setFieldsFilter(filteredUniqueFieldNames, true),
    disabled: fieldSearchText.length > 0 && filteredUniqueFieldNames.length === 0,
    "data-test-subj": "aiopsFieldSelectorSelectAllFieldsButton"
  }, fieldSearchText.length > 0 ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.logRateAnalysis.page.fieldSelector.selectAllSearchedFields",
    defaultMessage: "Select filtered fields"
  }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.logRateAnalysis.page.fieldSelector.selectAllFields",
    defaultMessage: "Select all fields"
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    size: "xs",
    flush: "right",
    onClick: () => setFieldsFilter(filteredUniqueFieldNames, false),
    disabled: fieldSearchText.length > 0 && filteredUniqueFieldNames.length === 0,
    "data-test-subj": "aiopsFieldSelectorDeselectAllFieldsButton"
  }, fieldSearchText.length > 0 ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.logRateAnalysis.page.fieldSelector.deselectAllSearchedFields",
    defaultMessage: "Deselect filtered fields"
  }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.logRateAnalysis.page.fieldSelector.deselectAllFields",
    defaultMessage: "Deselect all fields"
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_field_filter_apply_button.FieldFilterApplyButton, {
    onClick: () => {
      onChange(skippedFields);
      setFieldSearchText('');
      setIsFieldSelectionPopoverOpen(false);
      closePopover();
    },
    disabled: disabledApplyButton || selectedFieldCount < 2 || !isTouched,
    tooltipContent: selectedFieldCount < 2 ? _i18n.i18n.translate('xpack.aiops.analysis.fieldSelectorNotEnoughFieldsSelected', {
      defaultMessage: 'Grouping requires at least 2 fields to be selected.'
    }) : undefined
  })))));
};
exports.FieldFilterPopover = FieldFilterPopover;