"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LogRateAnalysisResults = void 0;
var _react = _interopRequireWildcard(require("react"));
var _lodash = require("lodash");
var _eui = require("@elastic/eui");
var _aiopsComponents = require("@kbn/aiops-components");
var _client = require("@kbn/ml-response-stream/client");
var _aiopsUtils = require("@kbn/aiops-utils");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _use_aiops_app_context = require("../../hooks/use_aiops_app_context");
var _stream_reducer = require("../../../common/api/stream_reducer");
var _constants = require("../../../common/constants");
var _log_rate_analysis_results_table = require("../log_rate_analysis_results_table");
var _log_rate_analysis_results_table_row_provider = require("../log_rate_analysis_results_table/log_rate_analysis_results_table_row_provider");
var _field_filter_popover = require("./field_filter_popover");
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 groupResultsMessage = _i18n.i18n.translate('xpack.aiops.logRateAnalysis.resultsTable.groupedSwitchLabel.groupResults', {
  defaultMessage: 'Smart grouping'
});
const groupResultsHelpMessage = _i18n.i18n.translate('xpack.aiops.logRateAnalysis.resultsTable.groupedSwitchLabel.groupResultsHelpMessage', {
  defaultMessage: 'Items which are unique to a group are marked by an asterisk (*).'
});
const groupResultsOffMessage = _i18n.i18n.translate('xpack.aiops.logRateAnalysis.resultsTable.groupedSwitchLabel.groupResultsOff', {
  defaultMessage: 'Off'
});
const groupResultsOnMessage = _i18n.i18n.translate('xpack.aiops.logRateAnalysis.resultsTable.groupedSwitchLabel.groupResultsOn', {
  defaultMessage: 'On'
});
const resultsGroupedOffId = 'aiopsLogRateAnalysisGroupingOff';
const resultsGroupedOnId = 'aiopsLogRateAnalysisGroupingOn';

/**
 * Interface for log rate analysis results data.
 */

/**
 * LogRateAnalysis props require a data view.
 */

const LogRateAnalysisResults = ({
  dataView,
  analysisType = _aiopsUtils.LOG_RATE_ANALYSIS_TYPE.SPIKE,
  earliest,
  isBrushCleared,
  latest,
  stickyHistogram,
  onReset,
  windowParameters,
  searchQuery,
  sampleProbability,
  barColorOverride,
  barHighlightColorOverride,
  onAnalysisCompleted,
  embeddingOrigin
}) => {
  var _dataView$timeFieldNa, _data$loadingState;
  const {
    http
  } = (0, _use_aiops_app_context.useAiopsAppContext)();
  const {
    clearAllRowState
  } = (0, _log_rate_analysis_results_table_row_provider.useLogRateAnalysisResultsTableRowContext)();
  const [currentAnalysisType, setCurrentAnalysisType] = (0, _react.useState)();
  const [currentAnalysisWindowParameters, setCurrentAnalysisWindowParameters] = (0, _react.useState)();
  const [groupResults, setGroupResults] = (0, _react.useState)(false);
  const [groupSkipFields, setGroupSkipFields] = (0, _react.useState)([]);
  const [uniqueFieldNames, setUniqueFieldNames] = (0, _react.useState)([]);
  const [overrides, setOverrides] = (0, _react.useState)(undefined);
  const [shouldStart, setShouldStart] = (0, _react.useState)(false);
  const [toggleIdSelected, setToggleIdSelected] = (0, _react.useState)(resultsGroupedOffId);
  const onGroupResultsToggle = optionId => {
    setToggleIdSelected(optionId);
    setGroupResults(optionId === resultsGroupedOnId);

    // When toggling the group switch, clear all row selections
    clearAllRowState();
  };
  const onFieldsFilterChange = skippedFields => {
    setGroupSkipFields(skippedFields);
    setOverrides({
      loaded: 0,
      remainingFieldCandidates: [],
      significantTerms: data.significantTerms.filter(d => !skippedFields.includes(d.fieldName)),
      regroupOnly: true
    });
    startHandler(true, false);
  };
  const {
    cancel,
    start,
    data,
    isRunning,
    errors: streamErrors
  } = (0, _client.useFetchStream)(http, '/internal/aiops/log_rate_analysis', '1', {
    start: earliest,
    end: latest,
    searchQuery: JSON.stringify(searchQuery),
    // TODO Handle data view without time fields.
    timeFieldName: (_dataView$timeFieldNa = dataView.timeFieldName) !== null && _dataView$timeFieldNa !== void 0 ? _dataView$timeFieldNa : '',
    index: dataView.getIndexPattern(),
    grouping: true,
    flushFix: true,
    // If analysis type is `spike`, pass on window parameters as is,
    // if it's `dip`, swap baseline and deviation.
    ...(analysisType === _aiopsUtils.LOG_RATE_ANALYSIS_TYPE.SPIKE ? windowParameters : {
      baselineMin: windowParameters.deviationMin,
      baselineMax: windowParameters.deviationMax,
      deviationMin: windowParameters.baselineMin,
      deviationMax: windowParameters.baselineMax
    }),
    overrides,
    sampleProbability
  }, {
    reducer: _stream_reducer.streamReducer,
    initialState: _stream_reducer.initialState
  }, {
    [_constants.AIOPS_TELEMETRY_ID.AIOPS_ANALYSIS_RUN_ORIGIN]: embeddingOrigin
  });
  const {
    significantTerms
  } = data;
  (0, _react.useEffect)(() => setUniqueFieldNames((0, _lodash.uniq)(significantTerms.map(d => d.fieldName)).sort()), [significantTerms]);
  (0, _react.useEffect)(() => {
    if (!isRunning) {
      const {
        loaded,
        remainingFieldCandidates,
        groupsMissing
      } = data;
      if (loaded < 1 && (Array.isArray(remainingFieldCandidates) && remainingFieldCandidates.length > 0 || groupsMissing)) {
        setOverrides({
          loaded,
          remainingFieldCandidates,
          significantTerms: data.significantTerms
        });
      } else {
        setOverrides(undefined);
        if (onAnalysisCompleted) {
          onAnalysisCompleted({
            analysisType,
            significantTerms: data.significantTerms,
            significantTermsGroups: data.significantTermsGroups
          });
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isRunning]);
  const errors = (0, _react.useMemo)(() => [...streamErrors, ...data.errors], [streamErrors, data.errors]);

  // Start handler clears possibly hovered or pinned
  // significant terms on analysis refresh.
  function startHandler(continueAnalysis = false, resetGroupButton = true) {
    if (!continueAnalysis) {
      setOverrides(undefined);
      setUniqueFieldNames([]);
    }

    // Reset grouping to false and clear all row selections when restarting the analysis.
    if (resetGroupButton) {
      setGroupResults(false);
      setToggleIdSelected(resultsGroupedOffId);
      clearAllRowState();
    }
    setCurrentAnalysisType(analysisType);
    setCurrentAnalysisWindowParameters(windowParameters);

    // We trigger hooks updates above so we cannot directly call `start()` here
    // because it would be run with stale arguments.
    setShouldStart(true);
  }
  (0, _react.useEffect)(() => {
    if (shouldStart) {
      start();
      setShouldStart(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shouldStart]);
  (0, _react.useEffect)(() => {
    setCurrentAnalysisType(analysisType);
    setCurrentAnalysisWindowParameters(windowParameters);
    start();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const groupTableItems = (0, _react.useMemo)(() => (0, _log_rate_analysis_results_table.getGroupTableItems)(data.significantTermsGroups), [data.significantTermsGroups]);
  const shouldRerunAnalysis = (0, _react.useMemo)(() => currentAnalysisWindowParameters !== undefined && !(0, _lodash.isEqual)(currentAnalysisWindowParameters, windowParameters), [currentAnalysisWindowParameters, windowParameters]);
  const showLogRateAnalysisResultsTable = (data === null || data === void 0 ? void 0 : data.significantTerms.length) > 0;
  const groupItemCount = groupTableItems.reduce((p, c) => {
    return p + c.groupItemsSortedByUniqueness.length;
  }, 0);
  const foundGroups = groupTableItems.length > 0 && groupItemCount > 0;
  const timeRangeMs = {
    from: earliest,
    to: latest
  };

  // Disable the grouping switch toggle only if no groups were found,
  // the toggle wasn't enabled already and no fields were selected to be skipped.
  const disabledGroupResultsSwitch = !foundGroups && !groupResults && groupSkipFields.length === 0;
  const toggleButtons = [{
    id: resultsGroupedOffId,
    label: groupResultsOffMessage,
    'data-test-subj': 'aiopsLogRateAnalysisGroupSwitchOff'
  }, {
    id: resultsGroupedOnId,
    label: groupResultsOnMessage,
    'data-test-subj': 'aiopsLogRateAnalysisGroupSwitchOn'
  }];
  return /*#__PURE__*/_react.default.createElement("div", {
    "data-test-subj": "aiopsLogRateAnalysisResults"
  }, /*#__PURE__*/_react.default.createElement(_aiopsComponents.ProgressControls, {
    isBrushCleared: isBrushCleared,
    progress: data.loaded,
    progressMessage: (_data$loadingState = data.loadingState) !== null && _data$loadingState !== void 0 ? _data$loadingState : '',
    isRunning: isRunning,
    onRefresh: () => startHandler(false),
    onCancel: cancel,
    onReset: onReset,
    shouldRerunAnalysis: shouldRerunAnalysis
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    display: "columnCompressedSwitch"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "s",
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    size: "xs"
  }, groupResultsMessage)), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonGroup, {
    "data-test-subj": `aiopsLogRateAnalysisGroupSwitch${groupResults ? ' checked' : ''}`,
    buttonSize: "s",
    isDisabled: disabledGroupResultsSwitch,
    legend: "Smart grouping",
    options: toggleButtons,
    idSelected: toggleIdSelected,
    onChange: onGroupResultsToggle
  }))))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_field_filter_popover.FieldFilterPopover, {
    disabled: !groupResults || isRunning,
    disabledApplyButton: isRunning,
    uniqueFieldNames: uniqueFieldNames,
    onChange: onFieldsFilterChange
  }))), showLogRateAnalysisResultsTable && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
    title: /*#__PURE__*/_react.default.createElement("span", {
      "data-test-subj": "aiopsAnalysisTypeCalloutTitle"
    }, currentAnalysisType === _aiopsUtils.LOG_RATE_ANALYSIS_TYPE.SPIKE ? _i18n.i18n.translate('xpack.aiops.analysis.analysisTypeSpikeCallOutTitle', {
      defaultMessage: 'Analysis type: Log rate spike'
    }) : _i18n.i18n.translate('xpack.aiops.analysis.analysisTypeDipCallOutTitle', {
      defaultMessage: 'Analysis type: Log rate dip'
    })),
    color: "primary",
    iconType: "pin",
    size: "s"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    size: "s"
  }, currentAnalysisType === _aiopsUtils.LOG_RATE_ANALYSIS_TYPE.SPIKE ? _i18n.i18n.translate('xpack.aiops.analysis.analysisTypeSpikeCallOutContent', {
    defaultMessage: 'The median log rate in the selected deviation time range is higher than the baseline. Therefore, the analysis results table shows statistically significant items within the deviation time range that are contributors to the spike. The "doc count" column refers to the amount of documents in the deviation time range.'
  }) : _i18n.i18n.translate('xpack.aiops.analysis.analysisTypeDipCallOutContent', {
    defaultMessage: 'The median log rate in the selected deviation time range is lower than the baseline. Therefore, the analysis results table shows statistically significant items within the baseline time range that are less in number or missing within the deviation time range. The "doc count" column refers to the amount of documents in the baseline time range.'
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xs"
  })), errors.length > 0 ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xs"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
    title: _i18n.i18n.translate('xpack.aiops.analysis.errorCallOutTitle', {
      defaultMessage: 'The following {errorCount, plural, one {error} other {errors}} occurred running the analysis.',
      values: {
        errorCount: errors.length
      }
    }),
    color: "warning",
    iconType: "warning",
    size: "s"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    size: "s"
  }, errors.length === 1 ? /*#__PURE__*/_react.default.createElement("p", null, errors[0]) : /*#__PURE__*/_react.default.createElement("ul", null, errors.map((e, i) => /*#__PURE__*/_react.default.createElement("li", {
    key: i
  }, e))), overrides !== undefined ? /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    "data-test-subj": "aiopsLogRateAnalysisResultsTryToContinueAnalysisButton",
    size: "s",
    onClick: () => startHandler(true)
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.aiops.logRateAnalysis.page.tryToContinueAnalysisButtonText",
    defaultMessage: "Try to continue analysis"
  }))) : null)), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xs"
  })) : null, showLogRateAnalysisResultsTable && groupResults && foundGroups && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xs"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    size: "xs"
  }, groupResults ? groupResultsHelpMessage : undefined)), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xs"
  }), !isRunning && !showLogRateAnalysisResultsTable && /*#__PURE__*/_react.default.createElement(_eui.EuiEmptyPrompt, {
    "data-test-subj": "aiopsNoResultsFoundEmptyPrompt",
    title: /*#__PURE__*/_react.default.createElement("h2", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.aiops.logRateAnalysis.page.noResultsPromptTitle",
      defaultMessage: "The analysis did not return any results."
    })),
    titleSize: "xs",
    body: /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.aiops.logRateAnalysis.page.noResultsPromptBody",
      defaultMessage: "Try to adjust the baseline and deviation time ranges and rerun the analysis. If you still get no results, there might be no statistically significant entities contributing to this deviation in log rate."
    }))
  }), /*#__PURE__*/_react.default.createElement("div", {
    style: stickyHistogram ? {
      height: '500px',
      overflowX: 'hidden',
      overflowY: 'auto',
      paddingTop: '20px'
    } : undefined
  }, showLogRateAnalysisResultsTable && groupResults ? /*#__PURE__*/_react.default.createElement(_log_rate_analysis_results_table.LogRateAnalysisResultsGroupsTable, {
    significantTerms: data.significantTerms,
    groupTableItems: groupTableItems,
    loading: isRunning,
    dataView: dataView,
    timeRangeMs: timeRangeMs,
    searchQuery: searchQuery,
    barColorOverride: barColorOverride,
    barHighlightColorOverride: barHighlightColorOverride
  }) : null, showLogRateAnalysisResultsTable && !groupResults ? /*#__PURE__*/_react.default.createElement(_log_rate_analysis_results_table.LogRateAnalysisResultsTable, {
    significantTerms: data.significantTerms,
    loading: isRunning,
    dataView: dataView,
    timeRangeMs: timeRangeMs,
    searchQuery: searchQuery,
    barColorOverride: barColorOverride,
    barHighlightColorOverride: barHighlightColorOverride
  }) : null));
};
exports.LogRateAnalysisResults = LogRateAnalysisResults;