"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DataDriftOverviewTable = void 0;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _eui = require("@elastic/eui");
var _field_type_icon = require("../common/components/field_type_icon");
var _i18n_constants = require("../../../common/i18n_constants");
var _constants = require("./constants");
var _use_current_eui_theme = require("../common/hooks/use_current_eui_theme");
var _types = require("./types");
var _data_drift_utils = require("./data_drift_utils");
var _single_distribution_chart = require("./charts/single_distribution_chart");
var _overlap_distribution_chart = require("./charts/overlap_distribution_chart");
var _data_drift_distribution_chart = require("./charts/data_drift_distribution_chart");
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 dataComparisonYesLabel = _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.fieldTypeYesLabel', {
  defaultMessage: 'Yes'
});
const dataComparisonNoLabel = _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.driftDetectedNoLabel', {
  defaultMessage: 'No'
});
const DataDriftOverviewTable = ({
  data,
  onTableChange,
  pagination,
  sorting,
  status
}) => {
  const euiTheme = (0, _use_current_eui_theme.useCurrentEuiTheme)();
  const colors = (0, _react.useMemo)(() => ({
    referenceColor: euiTheme.euiColorVis2,
    comparisonColor: euiTheme.euiColorVis1
  }), [euiTheme]);
  const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = (0, _react.useState)({});
  const referenceDistributionLabel = _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.dataComparisonDistributionLabel', {
    defaultMessage: '{label} distribution',
    values: {
      label: _constants.REFERENCE_LABEL
    }
  });
  const comparisonDistributionLabel = _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.dataComparisonDistributionLabel', {
    defaultMessage: '{label} distribution',
    values: {
      label: _constants.COMPARISON_LABEL
    }
  });
  (0, _react.useEffect)(() => {
    const updatedItemIdToExpandedRowMap = {
      ...itemIdToExpandedRowMap
    };
    // Update expanded row in case data is stale
    Object.keys(updatedItemIdToExpandedRowMap).forEach(itemId => {
      const item = data.find(d => d.featureName === itemId);
      if (item) {
        const {
          featureName
        } = item;
        updatedItemIdToExpandedRowMap[featureName] = /*#__PURE__*/_react.default.createElement(_data_drift_distribution_chart.DataDriftDistributionChart, {
          item: item,
          colors: colors,
          secondaryType: item.secondaryType
        });
      }
    });
    setItemIdToExpandedRowMap(updatedItemIdToExpandedRowMap);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data, colors]);
  const columns = [{
    align: 'left',
    width: '40px',
    isExpander: true,
    name: /*#__PURE__*/_react.default.createElement(_eui.EuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("span", null, _i18n_constants.EXPAND_ROW)),
    render: item => {
      const itemIdToExpandedRowMapValues = {
        ...itemIdToExpandedRowMap
      };
      return /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
        "data-test-subj": `dataDriftToggleDetails-${itemIdToExpandedRowMapValues[item.featureName] ? 'expanded' : 'collapsed'}`,
        onClick: () => toggleDetails(item),
        "aria-label": itemIdToExpandedRowMapValues[item.featureName] ? _i18n_constants.COLLAPSE_ROW : _i18n_constants.EXPAND_ROW,
        iconType: itemIdToExpandedRowMapValues[item.featureName] ? 'arrowDown' : 'arrowRight'
      });
    }
  }, {
    field: 'featureName',
    name: _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.fieldNameLabel', {
      defaultMessage: 'Name'
    }),
    'data-test-subj': 'mlDataDriftOverviewTableFeatureName',
    sortable: true,
    textOnly: true
  }, {
    field: 'secondaryType',
    name: _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.fieldTypeLabel', {
      defaultMessage: 'Type'
    }),
    'data-test-subj': 'mlDataDriftOverviewTableFeatureType',
    sortable: true,
    textOnly: true,
    render: secondaryType => {
      return /*#__PURE__*/_react.default.createElement(_field_type_icon.FieldTypeIcon, {
        type: secondaryType,
        tooltipEnabled: true
      });
    }
  }, {
    field: 'driftDetected',
    name: _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.driftDetectedLabel', {
      defaultMessage: 'Drift detected'
    }),
    'data-test-subj': 'mlDataDriftOverviewTableDriftDetected',
    sortable: true,
    textOnly: true,
    render: (driftDetected, item) => {
      // @ts-expect-error currently ES two_sided does return string NaN, will be fixed
      // NaN happens when the distributions are non overlapping. This means there is a drift.
      if (item.similarityTestPValue === 'NaN') return dataComparisonYesLabel;
      return /*#__PURE__*/_react.default.createElement("span", null, driftDetected ? dataComparisonYesLabel : dataComparisonNoLabel);
    }
  }, {
    field: 'similarityTestPValue',
    name: /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
      content: _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.pValueTooltip', {
        defaultMessage: 'Indicates how extreme the change is. Lower values indicate greater change.'
      })
    }, /*#__PURE__*/_react.default.createElement("span", null, _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.pValueLabel', {
      defaultMessage: 'Similarity p-value'
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      size: "s",
      color: "subdued",
      type: "questionInCircle",
      className: "eui-alignTop"
    }))),
    'data-test-subj': 'mlDataDriftOverviewTableSimilarityTestPValue',
    sortable: true,
    textOnly: true,
    render: similarityTestPValue => {
      return /*#__PURE__*/_react.default.createElement("span", null, (0, _data_drift_utils.formatSignificanceLevel)(similarityTestPValue));
    }
  }, {
    field: 'referenceHistogram',
    name: referenceDistributionLabel,
    'data-test-subj': 'mlDataDriftOverviewTableReferenceDistribution',
    sortable: false,
    render: (referenceHistogram, item) => {
      return /*#__PURE__*/_react.default.createElement("div", {
        css: {
          width: 100,
          height: 40
        }
      }, /*#__PURE__*/_react.default.createElement(_single_distribution_chart.SingleDistributionChart, {
        fieldType: item.fieldType,
        data: referenceHistogram,
        color: colors.referenceColor,
        name: referenceDistributionLabel,
        secondaryType: item.secondaryType
      }));
    }
  }, {
    field: 'comparisonHistogram',
    name: comparisonDistributionLabel,
    'data-test-subj': 'mlDataDriftOverviewTableDataComparisonDistributionChart',
    sortable: false,
    render: (comparisonDistribution, item) => {
      return /*#__PURE__*/_react.default.createElement("div", {
        css: {
          width: 100,
          height: 40
        }
      }, /*#__PURE__*/_react.default.createElement(_single_distribution_chart.SingleDistributionChart, {
        fieldType: item.fieldType,
        data: comparisonDistribution,
        color: colors.comparisonColor,
        name: comparisonDistributionLabel,
        secondaryType: item.secondaryType
      }));
    }
  }, {
    field: 'comparisonDistribution',
    name: 'Comparison',
    'data-test-subj': 'mlDataDriftOverviewTableDataComparisonDistributionChart',
    sortable: false,
    render: (comparisonDistribution, item) => {
      return /*#__PURE__*/_react.default.createElement("div", {
        css: {
          width: 100,
          height: 40
        }
      }, /*#__PURE__*/_react.default.createElement(_overlap_distribution_chart.OverlapDistributionComparison, {
        fieldName: item.featureName,
        fieldType: item.fieldType,
        data: comparisonDistribution,
        colors: colors,
        secondaryType: item.secondaryType
      }));
    }
  }];
  const getRowProps = item => {
    return {
      'data-test-subj': `mlDataDriftOverviewTableRow row-${item.featureName}`,
      className: 'mlDataDriftOverviewTableRow',
      onClick: () => {}
    };
  };
  const getCellProps = (item, column) => {
    const {
      field
    } = column;
    return {
      'data-test-subj': `mlDataDriftOverviewTableCell row-${item.featureName}-column-${String(field)}`,
      textOnly: true
    };
  };
  const toggleDetails = item => {
    const itemIdToExpandedRowMapValues = {
      ...itemIdToExpandedRowMap
    };
    if (itemIdToExpandedRowMapValues[item.featureName]) {
      delete itemIdToExpandedRowMapValues[item.featureName];
    } else {
      itemIdToExpandedRowMapValues[item.featureName] = /*#__PURE__*/_react.default.createElement(_data_drift_distribution_chart.DataDriftDistributionChart, {
        item: item,
        colors: colors,
        secondaryType: item.secondaryType
      });
    }
    setItemIdToExpandedRowMap(itemIdToExpandedRowMapValues);
  };
  const tableMessage = (0, _react.useMemo)(() => {
    switch (status) {
      case _types.FETCH_STATUS.NOT_INITIATED:
        return _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.dataComparisonRunAnalysisMsg', {
          defaultMessage: 'Run analysis to compare reference and comparison data'
        });
      case _types.FETCH_STATUS.LOADING:
        return _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.dataComparisonLoadingMsg', {
          defaultMessage: 'Analyzing'
        });
      default:
        return undefined;
    }
  }, [status]);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiInMemoryTable, {
    "data-test-subj": "mlDataDriftTable",
    tableCaption: _i18n.i18n.translate('xpack.dataVisualizer.dataDrift.dataDriftTableCaption', {
      defaultMessage: 'Data drift overview'
    }),
    items: data,
    rowHeader: "featureName",
    columns: columns,
    rowProps: getRowProps,
    cellProps: getCellProps,
    itemId: "featureName",
    itemIdToExpandedRowMap: itemIdToExpandedRowMap,
    isExpandable: true,
    sorting: sorting,
    onChange: onTableChange,
    pagination: pagination,
    loading: status === _types.FETCH_STATUS.LOADING,
    message: tableMessage
  });
};
exports.DataDriftOverviewTable = DataDriftOverviewTable;