"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LogCategorizationFlyout = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _esQuery = require("@kbn/es-query");
var _mlUrlState = require("@kbn/ml-url-state");
var _constants = require("../../../common/constants");
var _url_state = require("../../application/utils/url_state");
var _search_utils = require("../../application/utils/search_utils");
var _use_data = require("../../hooks/use_data");
var _use_search = require("../../hooks/use_search");
var _use_aiops_app_context = require("../../hooks/use_aiops_app_context");
var _use_categorize_request = require("./use_categorize_request");
var _category_table = require("./category_table");
var _information_text = require("./information_text");
var _sampling_menu = require("./sampling_menu");
var _technical_preview_badge = require("./technical_preview_badge");
var _loading_categorization = require("./loading_categorization");
var _use_validate_category_field = require("./use_validate_category_field");
var _category_validation_callout = require("./category_validation_callout");
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.
 */

const BAR_TARGET = 20;
const LogCategorizationFlyout = ({
  dataView,
  savedSearch,
  selectedField,
  onClose,
  embeddingOrigin
}) => {
  var _data$categories$leng, _data$categories;
  const {
    notifications: {
      toasts
    },
    data: {
      query: {
        getState,
        filterManager
      }
    },
    uiSettings
  } = (0, _use_aiops_app_context.useAiopsAppContext)();
  const {
    runValidateFieldRequest,
    cancelRequest: cancelValidationRequest
  } = (0, _use_validate_category_field.useValidateFieldRequest)();
  const {
    euiTheme
  } = (0, _eui.useEuiTheme)();
  const {
    filters,
    query
  } = (0, _react.useMemo)(() => getState(), [getState]);
  const mounted = (0, _react.useRef)(false);
  const {
    runCategorizeRequest,
    cancelRequest: cancelCategorizationRequest,
    randomSampler
  } = (0, _use_categorize_request.useCategorizeRequest)();
  const [stateFromUrl] = (0, _mlUrlState.usePageUrlState)('logCategorization', (0, _url_state.getDefaultLogCategorizationAppState)({
    searchQuery: (0, _search_utils.createMergedEsQuery)(query, filters, dataView, uiSettings)
  }));
  const [selectedCategory, setSelectedCategory] = (0, _react.useState)(null);
  const [selectedSavedSearch /* , setSelectedSavedSearch*/] = (0, _react.useState)(savedSearch);
  const [loading, setLoading] = (0, _react.useState)(true);
  const [eventRate, setEventRate] = (0, _react.useState)([]);
  const [pinnedCategory, setPinnedCategory] = (0, _react.useState)(null);
  const [data, setData] = (0, _react.useState)(null);
  const [fieldValidationResult, setFieldValidationResult] = (0, _react.useState)(null);
  const cancelRequest = (0, _react.useCallback)(() => {
    cancelValidationRequest();
    cancelCategorizationRequest();
  }, [cancelCategorizationRequest, cancelValidationRequest]);
  (0, _react.useEffect)(function cancelRequestOnLeave() {
    mounted.current = true;
    return () => {
      mounted.current = false;
      cancelRequest();
    };
  }, [cancelRequest, mounted]);
  const {
    searchQueryLanguage,
    searchString,
    searchQuery
  } = (0, _use_search.useSearch)({
    dataView,
    savedSearch: selectedSavedSearch
  }, stateFromUrl, true);
  const {
    documentStats,
    timefilter,
    earliest,
    latest,
    intervalMs,
    forceRefresh
  } = (0, _use_data.useData)(dataView, 'log_categorization', searchQuery, undefined, undefined, undefined, BAR_TARGET);
  const loadCategories = (0, _react.useCallback)(async () => {
    const {
      getIndexPattern,
      timeFieldName: timeField
    } = dataView;
    const index = getIndexPattern();
    if (selectedField === undefined || timeField === undefined) {
      return;
    }
    cancelRequest();
    setLoading(true);
    setData(null);
    setFieldValidationResult(null);
    try {
      const [validationResult, categorizationResult] = await Promise.all([runValidateFieldRequest(index, selectedField.name, timeField, earliest, latest, searchQuery, {
        [_constants.AIOPS_TELEMETRY_ID.AIOPS_ANALYSIS_RUN_ORIGIN]: embeddingOrigin
      }), runCategorizeRequest(index, selectedField.name, timeField, earliest, latest, searchQuery, intervalMs)]);
      if (mounted.current === true) {
        setFieldValidationResult(validationResult);
        setData({
          categories: categorizationResult.categories,
          sparkLines: categorizationResult.sparkLinesPerCategory
        });
      }
    } catch (error) {
      toasts.addError(error, {
        title: _i18n.i18n.translate('xpack.aiops.logCategorization.errorLoadingCategories', {
          defaultMessage: 'Error loading categories'
        })
      });
    }
    if (mounted.current === true) {
      setLoading(false);
    }
  }, [dataView, selectedField, cancelRequest, runValidateFieldRequest, earliest, latest, searchQuery, runCategorizeRequest, intervalMs, toasts, embeddingOrigin]);
  const onAddFilter = (0, _react.useCallback)((values, alias) => {
    const filter = (0, _esQuery.buildEmptyFilter)(false, dataView.id);
    if (alias) {
      filter.meta.alias = alias;
    }
    filter.query = values.query;
    filterManager.addFilters([filter]);
  }, [dataView, filterManager]);
  (0, _react.useEffect)(() => {
    var _documentStats$docume;
    if ((_documentStats$docume = documentStats.documentCountStats) !== null && _documentStats$docume !== void 0 && _documentStats$docume.buckets) {
      randomSampler.setDocCount(documentStats.totalCount);
      setEventRate(Object.entries(documentStats.documentCountStats.buckets).map(([key, docCount]) => ({
        key: +key,
        docCount
      })));
      setData(null);
      loadCategories();
    }
  }, [documentStats, earliest, latest, searchQueryLanguage, searchString, searchQuery, loadCategories, randomSampler]);
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlyoutHeader, {
    hasBorder: true
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "s",
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "m"
  }, /*#__PURE__*/_react.default.createElement("h2", {
    id: "flyoutTitle",
    "data-test-subj": "mlJobSelectorFlyoutTitle"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.categorizeFlyout.title",
    defaultMessage: "Pattern analysis of {name}",
    values: {
      name: selectedField.name
    }
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false,
    css: {
      marginTop: euiTheme.size.xs
    }
  }, /*#__PURE__*/_react.default.createElement(_technical_preview_badge.TechnicalPreviewBadge, null)), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_sampling_menu.SamplingMenu, {
    randomSampler: randomSampler,
    reload: () => forceRefresh()
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlyoutBody, {
    "data-test-subj": "mlJobSelectorFlyoutBody"
  }, /*#__PURE__*/_react.default.createElement(_category_validation_callout.FieldValidationCallout, {
    validationResults: fieldValidationResult
  }), loading === true ? /*#__PURE__*/_react.default.createElement(_loading_categorization.LoadingCategorization, {
    onClose: onClose
  }) : null, /*#__PURE__*/_react.default.createElement(_information_text.InformationText, {
    loading: loading,
    categoriesLength: (_data$categories$leng = data === null || data === void 0 ? void 0 : (_data$categories = data.categories) === null || _data$categories === void 0 ? void 0 : _data$categories.length) !== null && _data$categories$leng !== void 0 ? _data$categories$leng : null,
    eventRateLength: eventRate.length,
    fieldSelected: selectedField !== null
  }), loading === false && data !== null && data.categories.length > 0 ? /*#__PURE__*/_react.default.createElement(_category_table.CategoryTable, {
    categories: data.categories,
    aiopsListState: stateFromUrl,
    dataViewId: dataView.id,
    eventRate: eventRate,
    sparkLines: data.sparkLines,
    selectedField: selectedField,
    pinnedCategory: pinnedCategory,
    setPinnedCategory: setPinnedCategory,
    selectedCategory: selectedCategory,
    setSelectedCategory: setSelectedCategory,
    timefilter: timefilter,
    onAddFilter: onAddFilter,
    onClose: onClose,
    enableRowActions: false
  }) : null));
};
exports.LogCategorizationFlyout = LogCategorizationFlyout;