"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DataDriftView = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _aiopsComponents = require("@kbn/aiops-components");
var _lodash = require("lodash");
var _i18nReact = require("@kbn/i18n-react");
var _mlInMemoryTable = require("@kbn/ml-in-memory-table");
var _field_types_utils = require("../common/util/field_types_utils");
var _use_data_drift_result = require("./use_data_drift_result");
var _data_drift_overview_table = require("./data_drift_overview_table");
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 showOnlyDriftedFieldsOptionLabel = _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.showOnlyDriftedFieldsOptionLabel', {
  defaultMessage: 'Show only fields with drifted data'
});
// Data drift view
const DataDriftView = ({
  windowParameters,
  dataView,
  searchString,
  searchQueryLanguage,
  onReset,
  isBrushCleared,
  lastRefresh,
  onRefresh,
  initialSettings
}) => {
  var _result$progressMessa;
  const [showDataComparisonOnly, setShowDataComparisonOnly] = (0, _react.useState)(false);
  const [currentAnalysisWindowParameters, setCurrentAnalysisWindowParameters] = (0, _react.useState)(windowParameters);
  const [fetchInfo, setFetchIno] = (0, _react.useState)();
  const refresh = (0, _react.useCallback)(() => {
    setCurrentAnalysisWindowParameters(windowParameters);
    const mergedFields = [];
    if (dataView) {
      mergedFields.push(...dataView.fields.filter(f => f.aggregatable === true &&
      // @ts-ignore metadata does exist
      f.spec.metadata_field !== true && (0, _use_data_drift_result.getDataComparisonType)(f.type) !== 'unsupported' && mergedFields.findIndex(merged => merged.field === f.name) === -1).map(f => ({
        field: f.name,
        type: (0, _use_data_drift_result.getDataComparisonType)(f.type),
        secondaryType: (0, _field_types_utils.kbnTypeToSupportedType)(f),
        displayName: f.displayName
      })));
    }
    setFetchIno({
      fields: mergedFields,
      currentDataView: dataView,
      ...(windowParameters ? {
        timeRanges: {
          reference: {
            start: windowParameters.baselineMin,
            end: windowParameters.baselineMax
          },
          comparison: {
            start: windowParameters.deviationMin,
            end: windowParameters.deviationMax
          }
        }
      } : {})
    });
    if (onRefresh) {
      onRefresh();
    }
  }, [dataView, windowParameters, onRefresh]);
  const {
    result,
    cancelRequest
  } = (0, _use_data_drift_result.useFetchDataComparisonResult)({
    ...fetchInfo,
    initialSettings,
    lastRefresh,
    searchString,
    searchQueryLanguage
  });
  const filteredData = (0, _react.useMemo)(() => {
    if (!(result !== null && result !== void 0 && result.data)) return [];
    switch (showDataComparisonOnly) {
      case true:
        return result.data.filter(d => d.driftDetected === true);
      default:
        return result.data;
    }
  }, [result.data, showDataComparisonOnly]);
  const {
    onTableChange,
    pagination,
    sorting,
    setPageIndex
  } = (0, _mlInMemoryTable.useTableState)(filteredData, 'driftDetected', 'desc');
  const shouldRerunAnalysis = (0, _react.useMemo)(() => currentAnalysisWindowParameters !== undefined && !(0, _lodash.isEqual)(currentAnalysisWindowParameters, windowParameters), [currentAnalysisWindowParameters, windowParameters]);
  const onShowDataComparisonOnlyToggle = e => {
    setShowDataComparisonOnly(e.target.checked);
    setPageIndex(0);
  };
  const requiresWindowParameters = (dataView === null || dataView === void 0 ? void 0 : dataView.isTimeBased()) && windowParameters === undefined;
  return requiresWindowParameters ? /*#__PURE__*/_react.default.createElement(_eui.EuiEmptyPrompt, {
    color: "subdued",
    hasShadow: false,
    hasBorder: false,
    css: {
      minWidth: '100%'
    },
    title: /*#__PURE__*/_react.default.createElement("h2", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.dataVisualizer.dataDrift.emptyPromptTitle",
      defaultMessage: "Select a time range for reference and comparison data in the histogram chart to compare data distribution."
    })),
    titleSize: "xs",
    body: /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.dataVisualizer.dataDrift.emptyPromptBody",
      defaultMessage: "The Data Drift Viewer visualizes changes in the model input data, which can lead to model performance degradation over time. Detecting data drifts enables you to identify potential performance issues."
    })),
    "data-test-subj": "dataDriftNoWindowParametersEmptyPrompt"
  }) : /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_aiopsComponents.ProgressControls, {
    isBrushCleared: isBrushCleared,
    onReset: onReset,
    progress: result.loaded,
    progressMessage: (_result$progressMessa = result.progressMessage) !== null && _result$progressMessa !== void 0 ? _result$progressMessa : '',
    isRunning: result.loaded > 0 && result.loaded < 1,
    onRefresh: refresh,
    onCancel: cancelRequest,
    shouldRerunAnalysis: shouldRerunAnalysis,
    runAnalysisDisabled: !dataView || requiresWindowParameters
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    display: "columnCompressedSwitch"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiSwitch, {
    label: showOnlyDriftedFieldsOptionLabel,
    "aria-label": showOnlyDriftedFieldsOptionLabel,
    checked: showDataComparisonOnly,
    onChange: onShowDataComparisonOnlyToggle,
    compressed: true
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), result.error ? /*#__PURE__*/_react.default.createElement(_eui.EuiEmptyPrompt, {
    css: {
      minWidth: '100%'
    },
    color: "danger",
    title: /*#__PURE__*/_react.default.createElement("h2", null, result.error),
    titleSize: "xs",
    body: /*#__PURE__*/_react.default.createElement("span", null, result.errorBody)
  }) : /*#__PURE__*/_react.default.createElement(_data_drift_overview_table.DataDriftOverviewTable, {
    data: filteredData,
    onTableChange: onTableChange,
    pagination: pagination,
    sorting: sorting,
    setPageIndex: setPageIndex,
    status: result.status
  }));
};
exports.DataDriftView = DataDriftView;