"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PartitionsSelector = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _lodash = require("lodash");
var _usePrevious = _interopRequireDefault(require("react-use/lib/usePrevious"));
var _use_aiops_app_context = require("../../hooks/use_aiops_app_context");
var _use_cancellable_search = require("../../hooks/use_cancellable_search");
var _use_data_source = require("../../hooks/use_data_source");
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.
 */

function getQueryPayload(indexPattern, fieldName, queryString = '', selectedPartitions) {
  return {
    params: {
      index: indexPattern,
      size: 0,
      ...(selectedPartitions !== null && selectedPartitions !== void 0 && selectedPartitions.length ? {
        query: {
          bool: {
            must_not: [{
              terms: {
                [fieldName]: selectedPartitions
              }
            }]
          }
        }
      } : {}),
      aggs: {
        aggResults: {
          filter: {
            bool: {
              must: {
                wildcard: {
                  [fieldName]: {
                    value: `*${queryString}*`
                  }
                }
              }
            }
          },
          aggs: {
            partitionValues: {
              terms: {
                field: fieldName
              }
            }
          }
        }
      }
    }
  };
}
const PartitionsSelector = ({
  value,
  onChange,
  splitField,
  enableSearch = true
}) => {
  const {
    dataView
  } = (0, _use_data_source.useDataSource)();
  const {
    notifications: {
      toasts
    }
  } = (0, _use_aiops_app_context.useAiopsAppContext)();
  const prevSplitField = (0, _usePrevious.default)(splitField);
  const [options, setOptions] = (0, _react.useState)([]);
  const [isLoading, setIsLoading] = (0, _react.useState)(enableSearch);
  const {
    runRequest,
    cancelRequest
  } = (0, _use_cancellable_search.useCancellableSearch)();
  const fetchResults = (0, _react.useCallback)(async searchValue => {
    if (!enableSearch) return;
    cancelRequest();
    setIsLoading(true);
    try {
      const requestPayload = getQueryPayload(dataView.getIndexPattern(), splitField, searchValue, value);
      const result = await runRequest(requestPayload);
      if (result === null) {
        setOptions([]);
        return;
      }
      setOptions(result.rawResponse.aggregations.aggResults.partitionValues.buckets.map(v => ({
        value: v.key,
        label: v.key
      })));
    } catch (e) {
      toasts.addError(e, {
        title: _i18n.i18n.translate('xpack.aiops.changePointDetection.fetchPartitionsErrorTitle', {
          defaultMessage: 'Failed to fetch partitions'
        })
      });
    }
    setIsLoading(false);
  }, [enableSearch, cancelRequest, dataView, splitField, value, runRequest, toasts]);
  (0, _react.useEffect)(function onSplitFieldChange() {
    fetchResults('');
    if (prevSplitField !== undefined && splitField !== prevSplitField) {
      onChange([]);
    }
  }, [splitField, prevSplitField, fetchResults, onChange]);
  const selectedOptions = (0, _react.useMemo)(() => {
    return value.map(v => ({
      value: v,
      label: v
    }));
  }, [value]);
  const onChangeCallback = (0, _react.useCallback)(udpate => {
    onChange(udpate.map(v => v.value));
  }, [onChange]);
  const onSearchChange = (0, _react.useMemo)(() => (0, _lodash.debounce)(fetchResults, 500), [fetchResults]);
  const onCreateOption = (0, _react.useCallback)(v => {
    onChange([...value, v]);
  }, [onChange, value]);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    fullWidth: true,
    label: _i18n.i18n.translate('xpack.aiops.changePointDetection.partitionsLabel', {
      defaultMessage: 'Partitions'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiComboBox, {
    isLoading: isLoading,
    fullWidth: true,
    compressed: true,
    options: options,
    selectedOptions: selectedOptions,
    onChange: onChangeCallback,
    onSearchChange: enableSearch ? onSearchChange : undefined,
    onCreateOption: !enableSearch ? onCreateOption : undefined,
    isClearable: true,
    "data-test-subj": "aiopsChangePointPartitions"
  }));
};
exports.PartitionsSelector = PartitionsSelector;