"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LogCategorizationPage = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _mlUrlState = require("@kbn/ml-url-state");
var _constants = require("../../../common/constants");
var _use_data_source = require("../../hooks/use_data_source");
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 _url_state = require("../../application/utils/url_state");
var _search_panel = require("../search_panel");
var _page_header = require("../page_header");
var _use_categorize_request = require("./use_categorize_request");
var _category_table = require("./category_table");
var _document_count_chart = require("./document_count_chart");
var _information_text = require("./information_text");
var _sampling_menu = require("./sampling_menu");
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 DEFAULT_SELECTED_FIELD = 'message';
const LogCategorizationPage = ({
  embeddingOrigin
}) => {
  var _data$sparkLines, _data$categories$leng, _data$categories;
  const {
    notifications: {
      toasts
    }
  } = (0, _use_aiops_app_context.useAiopsAppContext)();
  const {
    dataView,
    savedSearch
  } = (0, _use_data_source.useDataSource)();
  const {
    runCategorizeRequest,
    cancelRequest: cancelCategorizationRequest,
    randomSampler
  } = (0, _use_categorize_request.useCategorizeRequest)();
  const {
    runValidateFieldRequest,
    cancelRequest: cancelValidationRequest
  } = (0, _use_validate_category_field.useValidateFieldRequest)();
  const [stateFromUrl, setUrlState] = (0, _mlUrlState.usePageUrlState)('logCategorization', (0, _url_state.getDefaultLogCategorizationAppState)());
  const [globalState, setGlobalState] = (0, _mlUrlState.useUrlState)('_g');
  const [selectedField, setSelectedField] = (0, _react.useState)();
  const [selectedCategory, setSelectedCategory] = (0, _react.useState)(null);
  const [selectedSavedSearch, setSelectedSavedSearch] = (0, _react.useState)(savedSearch);
  const [loading, setLoading] = (0, _react.useState)(false);
  const [totalCount, setTotalCount] = (0, _react.useState)(0);
  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)(() => {
    if (savedSearch) {
      setSelectedSavedSearch(savedSearch);
    }
  }, [savedSearch]);
  (0, _react.useEffect)(function cancelRequestOnLeave() {
    return () => {
      cancelRequest();
    };
  }, [cancelRequest]);
  const setSearchParams = (0, _react.useCallback)(searchParams => {
    // When the user loads saved search and then clear or modify the query
    // we should remove the saved search and replace it with the index pattern id
    if (selectedSavedSearch !== null) {
      setSelectedSavedSearch(null);
    }
    setUrlState({
      ...stateFromUrl,
      searchQuery: searchParams.searchQuery,
      searchString: searchParams.searchString,
      searchQueryLanguage: searchParams.queryLanguage,
      filters: searchParams.filters
    });
  }, [selectedSavedSearch, stateFromUrl, setUrlState]);
  const {
    searchQueryLanguage,
    searchString,
    searchQuery
  } = (0, _use_search.useSearch)({
    dataView,
    savedSearch: selectedSavedSearch
  }, stateFromUrl);
  const {
    documentStats,
    timefilter,
    earliest,
    latest,
    intervalMs
  } = (0, _use_data.useData)(dataView, 'log_categorization', searchQuery, setGlobalState, undefined, undefined, BAR_TARGET);
  (0, _react.useEffect)(() => {
    if ((globalState === null || globalState === void 0 ? void 0 : globalState.time) !== undefined) {
      timefilter.setTime({
        from: globalState.time.from,
        to: globalState.time.to
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(globalState === null || globalState === void 0 ? void 0 : globalState.time), timefilter]);
  const fields = (0, _react.useMemo)(() => dataView.fields.filter(({
    displayName,
    esTypes,
    count
  }) => esTypes && esTypes.includes('text') && !['_id', '_index'].includes(displayName)).map(({
    displayName
  }) => ({
    label: displayName
  })), [dataView]);
  (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);
      setFieldValidationResult(null);
      setTotalCount(documentStats.totalCount);
    }
  }, [documentStats, earliest, latest, searchQueryLanguage, searchString, searchQuery, randomSampler]);
  const loadCategories = (0, _react.useCallback)(async () => {
    setLoading(true);
    setData(null);
    setFieldValidationResult(null);
    const {
      getIndexPattern,
      timeFieldName: timeField
    } = dataView;
    const index = getIndexPattern();
    if (selectedField === undefined || timeField === undefined) {
      setLoading(false);
      return;
    }
    cancelRequest();
    try {
      const [validationResult, categorizationResult] = await Promise.all([runValidateFieldRequest(index, selectedField, timeField, earliest, latest, searchQuery, {
        [_constants.AIOPS_TELEMETRY_ID.AIOPS_ANALYSIS_RUN_ORIGIN]: embeddingOrigin
      }), runCategorizeRequest(index, selectedField, timeField, earliest, latest, searchQuery, intervalMs)]);
      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'
        })
      });
    }
    setLoading(false);
  }, [dataView, selectedField, cancelRequest, runValidateFieldRequest, earliest, latest, searchQuery, runCategorizeRequest, intervalMs, toasts, embeddingOrigin]);
  (0, _react.useEffect)(function autoSelectField() {
    if (selectedField !== undefined) {
      return;
    }
    const field = stateFromUrl.field;
    if (field !== undefined && fields.find(f => f.label === field)) {
      // select field from URL, if it exists
      setSelectedField(field);
    } else if (fields.length === 1) {
      // otherwise, if there is only one field in the list, select it
      setSelectedField(fields[0].label);
    } else if (fields.find(f => f.label === DEFAULT_SELECTED_FIELD)) {
      // otherwise, if there is a field called `message`, select it
      setSelectedField(DEFAULT_SELECTED_FIELD);
    }
  }, [fields, loadCategories, selectedField, stateFromUrl.field]);
  const onFieldChange = value => {
    setData(null);
    setFieldValidationResult(null);
    const field = value && value.length ? value[0].label : undefined;
    setSelectedField(field);
    setUrlState({
      field
    });
  };
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPageBody, {
    "data-test-subj": "aiopsLogPatternAnalysisPage",
    paddingSize: "none",
    panelled: false
  }, /*#__PURE__*/_react.default.createElement(_page_header.PageHeader, null), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "none"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_search_panel.SearchPanel, {
    dataView: dataView,
    searchString: searchString !== null && searchString !== void 0 ? searchString : '',
    searchQuery: searchQuery,
    searchQueryLanguage: searchQueryLanguage,
    setSearchParams: setSearchParams
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "none"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false,
    css: {
      minWidth: '410px'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    label: _i18n.i18n.translate('xpack.aiops.logCategorization.categoryFieldSelect', {
      defaultMessage: 'Category field'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiComboBox, {
    isDisabled: loading === true,
    options: fields,
    onChange: onFieldChange,
    selectedOptions: selectedField === undefined ? undefined : [{
      label: selectedField
    }],
    singleSelection: {
      asPlainText: true
    },
    "data-test-subj": "aiopsLogPatternAnalysisCategoryField"
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false,
    css: {
      marginTop: 'auto'
    }
  }, loading === false ? /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    disabled: selectedField === undefined,
    onClick: () => {
      loadCategories();
    },
    "data-test-subj": "aiopsLogPatternAnalysisRunButton"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.logCategorization.runButton",
    defaultMessage: "Run pattern analysis"
  })) : /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    "data-test-subj": "aiopsLogCategorizationPageCancelButton",
    onClick: () => cancelRequest()
  }, "Cancel")), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false,
    css: {
      marginTop: 'auto'
    }
  }, /*#__PURE__*/_react.default.createElement(_sampling_menu.SamplingMenu, {
    randomSampler: randomSampler,
    reload: () => loadCategories()
  }))), eventRate.length ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), /*#__PURE__*/_react.default.createElement(_document_count_chart.DocumentCountChart, {
    eventRate: eventRate,
    pinnedCategory: pinnedCategory,
    selectedCategory: selectedCategory,
    sparkLines: (_data$sparkLines = data === null || data === void 0 ? void 0 : data.sparkLines) !== null && _data$sparkLines !== void 0 ? _data$sparkLines : {},
    totalCount: totalCount,
    documentCountStats: documentStats.documentCountStats
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null)) : null, /*#__PURE__*/_react.default.createElement(_category_validation_callout.FieldValidationCallout, {
    validationResults: fieldValidationResult
  }), loading === true ? /*#__PURE__*/_react.default.createElement(_eui.EuiSkeletonText, {
    lines: 10
  }) : 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
  }), selectedField !== undefined && 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
  }) : null);
};
exports.LogCategorizationPage = LogCategorizationPage;