"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PageHeader = exports.DataDriftPage = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _mlUrlState = require("@kbn/ml-url-state");
var _mlLocalStorage = require("@kbn/ml-local-storage");
var _mlDatePicker = require("@kbn/ml-date-picker");
var _moment = _interopRequireDefault(require("moment"));
var _react2 = require("@emotion/react");
var _i18n = require("@kbn/i18n");
var _use_state_manager = require("./use_state_manager");
var _use_data = require("../common/hooks/use_data");
var _storage = require("../index_data_visualizer/types/storage");
var _use_current_eui_theme = require("../common/hooks/use_current_eui_theme");
var _types = require("./types");
var _data_source_context = require("../common/hooks/data_source_context");
var _kibana_context = require("../kibana_context");
var _data_drift_view = require("./data_drift_view");
var _constants = require("./constants");
var _search_bar = require("../index_data_visualizer/components/search_panel/search_bar");
var _use_search = require("../common/hooks/use_search");
var _document_count_with_dual_brush = require("./document_count_with_dual_brush");
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 dataViewTitleHeader = (0, _react2.css)({
  minWidth: '300px'
});
const PageHeader = () => {
  const [, setGlobalState] = (0, _mlUrlState.useUrlState)('_g');
  const {
    dataView
  } = (0, _data_source_context.useDataSource)();
  const [frozenDataPreference, setFrozenDataPreference] = (0, _mlLocalStorage.useStorage)(_storage.DV_FROZEN_TIER_PREFERENCE,
  // By default we will exclude frozen data tier
  _mlDatePicker.FROZEN_TIER_PREFERENCE.EXCLUDE);
  const timefilter = (0, _mlDatePicker.useTimefilter)({
    timeRangeSelector: dataView.timeFieldName !== undefined,
    autoRefreshSelector: true
  });
  const updateTimeState = (0, _react.useCallback)(update => {
    setGlobalState({
      time: {
        from: (0, _moment.default)(update.start.epoch).toISOString(),
        to: (0, _moment.default)(update.end.epoch).toISOString()
      }
    });
  }, [setGlobalState]);
  const hasValidTimeField = (0, _react.useMemo)(() => dataView.timeFieldName !== undefined && dataView.timeFieldName !== '', [dataView.timeFieldName]);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPageHeader, {
    pageTitle: /*#__PURE__*/_react.default.createElement("div", {
      "data-test-subj": 'mlDataDriftPageDataViewTitle',
      css: dataViewTitleHeader
    }, dataView.getName()),
    rightSideItems: [/*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      gutterSize: "s",
      "data-test-subj": "dataComparisonTimeRangeSelectorSection"
    }, hasValidTimeField ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_mlDatePicker.FullTimeRangeSelector, {
      frozenDataPreference: frozenDataPreference,
      setFrozenDataPreference: setFrozenDataPreference,
      dataView: dataView,
      query: undefined,
      disabled: false,
      timefilter: timefilter,
      callback: updateTimeState
    })) : null, /*#__PURE__*/_react.default.createElement(_mlDatePicker.DatePickerWrapper, {
      isAutoRefreshOnly: !hasValidTimeField,
      showRefresh: !hasValidTimeField,
      width: "full",
      flexGroup: false
    }))]
  });
};
exports.PageHeader = PageHeader;
const getDataDriftDataLabel = (label, indexPattern) => _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.dataLabel', {
  defaultMessage: '{label} data',
  values: {
    label
  }
}) + (indexPattern ? `: ${indexPattern}` : '');
const DataDriftPage = ({
  initialSettings
}) => {
  const {
    services: {
      data: dataService
    }
  } = (0, _kibana_context.useDataVisualizerKibana)();
  const {
    dataView,
    savedSearch
  } = (0, _data_source_context.useDataSource)();
  const {
    reference: referenceStateManager,
    comparison: comparisonStateManager
  } = (0, _use_state_manager.useDataDriftStateManagerContext)();
  const [dataComparisonListState, setDataComparisonListState] = (0, _mlUrlState.usePageUrlState)('DV_DATA_DRIFT', (0, _types.getDefaultDataComparisonState)());
  const [lastRefresh, setLastRefresh] = (0, _react.useState)(0);
  const forceRefresh = (0, _react.useCallback)(() => setLastRefresh(Date.now()), [setLastRefresh]);
  const randomSampler = (0, _react.useMemo)(() => referenceStateManager.randomSampler, [referenceStateManager]);
  const randomSamplerProd = (0, _react.useMemo)(() => comparisonStateManager.randomSampler, [comparisonStateManager]);
  const [globalState, setGlobalState] = (0, _mlUrlState.useUrlState)('_g');
  const [selectedSavedSearch, setSelectedSavedSearch] = (0, _react.useState)(savedSearch);
  (0, _react.useEffect)(() => {
    if (savedSearch) {
      setSelectedSavedSearch(savedSearch);
    }
  }, [savedSearch]);
  const setSearchParams = (0, _react.useCallback)(searchParams => {
    // When the user loads a saved search and then clears or modifies the query
    // we should remove the saved search and replace it with the index pattern id
    if (selectedSavedSearch !== null) {
      setSelectedSavedSearch(null);
    }
    setDataComparisonListState({
      ...dataComparisonListState,
      searchQuery: searchParams.searchQuery,
      searchString: searchParams.searchString,
      searchQueryLanguage: searchParams.queryLanguage,
      filters: searchParams.filters
    });
  }, [selectedSavedSearch, dataComparisonListState, setDataComparisonListState]);
  const {
    searchQueryLanguage,
    searchString,
    searchQuery
  } = (0, _use_search.useSearch)({
    dataView,
    savedSearch
  }, dataComparisonListState);
  const {
    documentStats,
    documentStatsProd,
    timefilter
  } = (0, _use_data.useData)(initialSettings, dataView, 'data_drift', searchString, searchQueryLanguage, randomSampler, randomSamplerProd, setGlobalState, undefined);
  const {
    sampleProbability,
    totalCount,
    documentCountStats,
    documentCountStatsCompare
  } = documentStats;
  (0, _react.useEffect)(() => {
    randomSampler.setDocCount(totalCount);
  }, [totalCount, randomSampler]);
  (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]);
  (0, _react.useEffect)(() => {
    if ((globalState === null || globalState === void 0 ? void 0 : globalState.refreshInterval) !== undefined) {
      timefilter.setRefreshInterval(globalState.refreshInterval);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(globalState === null || globalState === void 0 ? void 0 : globalState.refreshInterval), timefilter]);
  (0, _react.useEffect)(() => {
    // Update data query manager if input string is updated
    dataService === null || dataService === void 0 ? void 0 : dataService.query.queryString.setQuery({
      query: searchString !== null && searchString !== void 0 ? searchString : '',
      language: searchQueryLanguage
    });
  }, [dataService, searchQueryLanguage, searchString]);
  const euiTheme = (0, _use_current_eui_theme.useCurrentEuiTheme)();
  const colors = {
    referenceColor: euiTheme.euiColorVis2,
    comparisonColor: euiTheme.euiColorVis1
  };
  const [windowParameters, setWindowParameters] = (0, _react.useState)();
  const [initialAnalysisStart, setInitialAnalysisStart] = (0, _react.useState)();
  const [isBrushCleared, setIsBrushCleared] = (0, _react.useState)(true);
  function brushSelectionUpdate(d, force) {
    if (!isBrushCleared || force) {
      setWindowParameters(d);
    }
    if (force) {
      setIsBrushCleared(false);
    }
  }
  function clearSelection() {
    setWindowParameters(undefined);
    setIsBrushCleared(true);
    setInitialAnalysisStart(undefined);
  }
  const barStyleAccessor = (0, _react.useCallback)(datum => {
    var _documentCountStats$i;
    if (!windowParameters) return null;
    const start = datum.x;
    const end = (typeof datum.x === 'string' ? parseInt(datum.x, 10) : datum.x) + ((_documentCountStats$i = documentCountStats === null || documentCountStats === void 0 ? void 0 : documentCountStats.interval) !== null && _documentCountStats$i !== void 0 ? _documentCountStats$i : 0);
    if (start >= windowParameters.baselineMin && end <= windowParameters.baselineMax) {
      return colors.referenceColor;
    }
    if (start >= windowParameters.deviationMin && end <= windowParameters.deviationMax) {
      return colors.comparisonColor;
    }
    return null;
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [JSON.stringify({
    windowParameters,
    colors
  })]);
  const referenceIndexPatternLabel = initialSettings !== null && initialSettings !== void 0 && initialSettings.reference ? getDataDriftDataLabel(_constants.REFERENCE_LABEL, initialSettings.reference) : getDataDriftDataLabel(_constants.REFERENCE_LABEL);
  const comparisonIndexPatternLabel = initialSettings !== null && initialSettings !== void 0 && initialSettings.comparison ? getDataDriftDataLabel(_constants.COMPARISON_LABEL, initialSettings === null || initialSettings === void 0 ? void 0 : initialSettings.comparison) : getDataDriftDataLabel(_constants.COMPARISON_LABEL);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPageBody, {
    "data-test-subj": "dataComparisonDataDriftPage",
    paddingSize: "none",
    panelled: false
  }, /*#__PURE__*/_react.default.createElement(PageHeader, null), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiPageSection, {
    paddingSize: "none"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "m",
    direction: "column"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_search_bar.SearchPanelContent, {
    dataView: dataView,
    searchString: searchString,
    searchQuery: searchQuery,
    searchQueryLanguage: searchQueryLanguage,
    setSearchParams: setSearchParams
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    paddingSize: "m"
  }, /*#__PURE__*/_react.default.createElement(_document_count_with_dual_brush.DocumentCountWithDualBrush, {
    id: _constants.REFERENCE_LABEL,
    label: referenceIndexPatternLabel,
    randomSampler: randomSampler,
    reload: forceRefresh,
    brushSelectionUpdateHandler: brushSelectionUpdate,
    documentCountStats: documentCountStats,
    documentCountStatsSplit: documentCountStatsCompare,
    isBrushCleared: isBrushCleared,
    totalCount: totalCount,
    approximate: sampleProbability < 1,
    sampleProbability: sampleProbability,
    initialAnalysisStart: initialAnalysisStart,
    barStyleAccessor: barStyleAccessor,
    baselineBrush: {
      label: _constants.REFERENCE_LABEL,
      annotationStyle: {
        strokeWidth: 0,
        stroke: colors.referenceColor,
        fill: colors.referenceColor,
        opacity: 0.5
      },
      badgeWidth: 80
    },
    deviationBrush: {
      label: _constants.COMPARISON_LABEL,
      annotationStyle: {
        strokeWidth: 0,
        stroke: colors.comparisonColor,
        fill: colors.comparisonColor,
        opacity: 0.5
      },
      badgeWidth: 90
    },
    stateManager: referenceStateManager
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiHorizontalRule, null), /*#__PURE__*/_react.default.createElement(_document_count_with_dual_brush.DocumentCountWithDualBrush, {
    id: _constants.COMPARISON_LABEL,
    label: comparisonIndexPatternLabel,
    randomSampler: randomSamplerProd,
    reload: forceRefresh,
    documentCountStats: documentStatsProd.documentCountStats,
    documentCountStatsSplit: documentStatsProd.documentCountStatsCompare,
    isBrushCleared: isBrushCleared,
    totalCount: documentStatsProd.totalCount,
    approximate: documentStatsProd.sampleProbability < 1,
    sampleProbability: documentStatsProd.sampleProbability,
    initialAnalysisStart: initialAnalysisStart,
    barStyleAccessor: barStyleAccessor,
    baselineBrush: {
      label: _constants.REFERENCE_LABEL,
      annotationStyle: {
        strokeWidth: 0,
        stroke: colors.referenceColor,
        fill: colors.referenceColor,
        opacity: 0.5
      },
      badgeWidth: 80
    },
    deviationBrush: {
      label: _constants.COMPARISON_LABEL,
      annotationStyle: {
        strokeWidth: 0,
        stroke: colors.comparisonColor,
        fill: colors.comparisonColor,
        opacity: 0.5
      },
      badgeWidth: 90
    },
    stateManager: comparisonStateManager
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    paddingSize: "m"
  }, /*#__PURE__*/_react.default.createElement(_data_drift_view.DataDriftView, {
    initialSettings: initialSettings,
    isBrushCleared: isBrushCleared,
    onReset: clearSelection,
    windowParameters: windowParameters,
    dataView: dataView,
    searchString: searchString !== null && searchString !== void 0 ? searchString : '',
    searchQueryLanguage: searchQueryLanguage,
    lastRefresh: lastRefresh,
    onRefresh: forceRefresh
  }))))));
};
exports.DataDriftPage = DataDriftPage;