"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DataVisualizerTable = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _lodash = require("lodash");
var _react2 = require("@emotion/react");
var _constants = require("../../../../../common/constants");
var _document_stats = require("./components/field_data_row/document_stats");
var _number_content_preview = require("./components/field_data_row/number_content_preview");
var _use_table_settings = require("./use_table_settings");
var _top_values_preview = require("./components/field_data_row/top_values_preview");
var _field_vis_config = require("../../../../../common/types/field_vis_config");
var _field_data_row = require("../field_data_row");
var _field_data_row2 = require("./components/field_data_row");
var _utils = require("./utils");
var _distinct_values = require("./components/field_data_row/distinct_values");
var _field_type_icon = require("../field_type_icon");
require("./_index.scss");
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 FIELD_NAME = 'fieldName';
const DataVisualizerTable = ({
  items,
  pageState,
  updatePageState,
  getItemIdToExpandedRowMap,
  extendedColumns,
  showPreviewByDefault,
  onChange,
  loading,
  totalCount,
  overallStatsRunning
}) => {
  const {
    euiTheme
  } = (0, _eui.useEuiTheme)();
  const [expandedRowItemIds, setExpandedRowItemIds] = (0, _react.useState)([]);
  const [expandAll, setExpandAll] = (0, _react.useState)(false);
  const {
    onTableChange,
    pagination,
    sorting
  } = (0, _use_table_settings.useTableSettings)(items, pageState, updatePageState);
  const [showDistributions, setShowDistributions] = (0, _react.useState)(showPreviewByDefault !== null && showPreviewByDefault !== void 0 ? showPreviewByDefault : true);
  const [dimensions, setDimensions] = (0, _react.useState)((0, _utils.calculateTableColumnsDimensions)());
  const toggleExpandAll = (0, _react.useCallback)(shouldExpandAll => {
    setExpandedRowItemIds(shouldExpandAll ?
    // Update list of ids in expandedRowIds to include all
    items.map(item => item.fieldName).filter(id => id !== undefined) :
    // Otherwise, reset list of ids in expandedRowIds
    []);
    setExpandAll(shouldExpandAll);
  }, [items]);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const resizeHandler = (0, _react.useCallback)((0, _lodash.throttle)(e => {
    // When window or table is resized,
    // update the column widths and other settings accordingly
    setDimensions((0, _utils.calculateTableColumnsDimensions)(e.width));
  }, 500), []);
  const toggleShowDistribution = (0, _react.useCallback)(() => {
    setShowDistributions(!showDistributions);
    if (onChange) {
      onChange({
        showDistributions: !showDistributions
      });
    }
  }, [onChange, showDistributions]);
  function toggleDetails(item) {
    if (item.fieldName === undefined) return;
    const index = expandedRowItemIds.indexOf(item.fieldName);
    if (index !== -1) {
      expandedRowItemIds.splice(index, 1);
    } else {
      expandedRowItemIds.push(item.fieldName);
    }

    // spread to a new array otherwise the component wouldn't re-render
    setExpandedRowItemIds([...expandedRowItemIds]);
  }
  const columns = (0, _react.useMemo)(() => {
    const expanderColumn = {
      name:
      // EUI will automatically show an expander button when table is mobile view (where width <700)
      // so we need to not render any addition button
      dimensions.breakPoint !== 'small' ? /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
        "data-test-subj": `dataVisualizerToggleDetailsForAllRowsButton ${expandAll ? 'expanded' : 'collapsed'}`,
        onClick: () => toggleExpandAll(!expandAll),
        "aria-label": !expandAll ? _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.expandDetailsForAllAriaLabel', {
          defaultMessage: 'Expand details for all fields'
        }) : _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.collapseDetailsForAllAriaLabel', {
          defaultMessage: 'Collapse details for all fields'
        }),
        iconType: expandAll ? 'arrowDown' : 'arrowRight'
      }) : null,
      align: _eui.RIGHT_ALIGNMENT,
      width: dimensions.expander,
      isExpander: true,
      render: item => {
        var _item$displayName;
        const displayName = (_item$displayName = item.displayName) !== null && _item$displayName !== void 0 ? _item$displayName : item.fieldName;
        if (item.fieldName === undefined) return null;
        const direction = expandedRowItemIds.includes(item.fieldName) ? 'arrowDown' : 'arrowRight';
        return /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
          "data-test-subj": `dataVisualizerDetailsToggle-${item.fieldName}-${direction}`,
          onClick: () => toggleDetails(item),
          "aria-label": expandedRowItemIds.includes(item.fieldName) ? _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.rowCollapse', {
            defaultMessage: 'Hide details for {fieldName}',
            values: {
              fieldName: displayName
            }
          }) : _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.rowExpand', {
            defaultMessage: 'Show details for {fieldName}',
            values: {
              fieldName: displayName
            }
          }),
          iconType: direction
        });
      },
      'data-test-subj': 'dataVisualizerTableColumnDetailsToggle'
    };
    const baseColumns = [expanderColumn, {
      field: 'type',
      name: _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.typeColumnName', {
        defaultMessage: 'Type'
      }),
      render: (fieldType, item) => {
        var _item$secondaryType;
        return /*#__PURE__*/_react.default.createElement(_field_type_icon.FieldTypeIcon, {
          type: (_item$secondaryType = item.secondaryType) !== null && _item$secondaryType !== void 0 ? _item$secondaryType : fieldType,
          tooltipEnabled: true
        });
      },
      width: dimensions.type,
      sortable: true,
      align: _eui.CENTER_ALIGNMENT,
      'data-test-subj': 'dataVisualizerTableColumnType'
    }, {
      field: 'fieldName',
      name: _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.nameColumnName', {
        defaultMessage: 'Name'
      }),
      sortable: true,
      truncateText: true,
      render: (fieldName, item) => {
        var _item$displayName2;
        const displayName = (_item$displayName2 = item.displayName) !== null && _item$displayName2 !== void 0 ? _item$displayName2 : item.fieldName;
        return /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
          size: "xs",
          "data-test-subj": `dataVisualizerDisplayName-${item.fieldName}`
        }, displayName);
      },
      align: _eui.LEFT_ALIGNMENT,
      'data-test-subj': 'dataVisualizerTableColumnName'
    }, {
      field: 'docCount',
      name: /*#__PURE__*/_react.default.createElement("div", {
        className: 'columnHeader__title'
      }, _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.documentsCountColumnName', {
        defaultMessage: 'Documents (%)'
      }), /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
        content: _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.documentsCountColumnTooltip', {
          defaultMessage: 'Document count found is based on a smaller set of sampled records.'
        })
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        type: "questionInCircle"
      }))),
      render: (value, item) => {
        if (overallStatsRunning) {
          return /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
            textAlign: "center"
          }, /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingSpinner, {
            size: "s"
          }));
        }
        return /*#__PURE__*/_react.default.createElement(_document_stats.DocumentStat, {
          config: item,
          showIcon: dimensions.showIcon,
          totalCount: totalCount
        });
      },
      sortable: item => {
        var _item$stats;
        return item === null || item === void 0 ? void 0 : (_item$stats = item.stats) === null || _item$stats === void 0 ? void 0 : _item$stats.count;
      },
      align: _eui.LEFT_ALIGNMENT,
      'data-test-subj': 'dataVisualizerTableColumnDocumentsCount',
      width: dimensions.docCount
    }, {
      field: 'cardinality',
      name: _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.distinctValuesColumnName', {
        defaultMessage: 'Distinct values'
      }),
      render: (_, item) => {
        var _item$stats2;
        if (overallStatsRunning) {
          return /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
            textAlign: "center"
          }, /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingSpinner, {
            size: "s"
          }));
        }
        return /*#__PURE__*/_react.default.createElement(_distinct_values.DistinctValues, {
          cardinality: item === null || item === void 0 ? void 0 : (_item$stats2 = item.stats) === null || _item$stats2 === void 0 ? void 0 : _item$stats2.cardinality,
          showIcon: dimensions.showIcon
        });
      },
      sortable: item => {
        var _item$stats3;
        return item === null || item === void 0 ? void 0 : (_item$stats3 = item.stats) === null || _item$stats3 === void 0 ? void 0 : _item$stats3.cardinality;
      },
      align: _eui.LEFT_ALIGNMENT,
      'data-test-subj': 'dataVisualizerTableColumnDistinctValues',
      width: dimensions.distinctValues
    }, {
      name: /*#__PURE__*/_react.default.createElement("div", {
        className: 'columnHeader__title'
      }, dimensions.showIcon ? /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        type: 'visBarVertical',
        className: 'columnHeader__icon'
      }) : null, _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.distributionsColumnName', {
        defaultMessage: 'Distributions'
      }), /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
        content: !showDistributions ? _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.showDistributionsTooltip', {
          defaultMessage: 'Show distributions'
        }) : _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.hideDistributionsTooltip', {
          defaultMessage: 'Hide distributions'
        })
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
        style: {
          marginLeft: 4
        },
        size: 's',
        iconType: !showDistributions ? 'eye' : 'eyeClosed',
        onClick: () => toggleShowDistribution(),
        "aria-label": showDistributions ? _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.showDistributionsAriaLabel', {
          defaultMessage: 'Show distributions'
        }) : _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.hideDistributionsAriaLabel', {
          defaultMessage: 'Hide distributions'
        })
      }))),
      render: item => {
        var _item$stats4;
        if (item === undefined || showDistributions === false) return null;
        if ('loading' in item && item.loading === true) {
          return /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
            textAlign: "center"
          }, /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingSpinner, {
            size: "s"
          }));
        }
        if ((item.type === _constants.SUPPORTED_FIELD_TYPES.KEYWORD || item.type === _constants.SUPPORTED_FIELD_TYPES.IP) && ((_item$stats4 = item.stats) === null || _item$stats4 === void 0 ? void 0 : _item$stats4.topValues) !== undefined) {
          return /*#__PURE__*/_react.default.createElement(_top_values_preview.TopValuesPreview, {
            config: item
          });
        }
        if (item.type === _constants.SUPPORTED_FIELD_TYPES.NUMBER) {
          var _item$stats5;
          if ((0, _field_vis_config.isIndexBasedFieldVisConfig)(item) && ((_item$stats5 = item.stats) === null || _item$stats5 === void 0 ? void 0 : _item$stats5.distribution) !== undefined) {
            var _item$stats6, _item$stats6$distribu;
            // If the cardinality is only low, show the top values instead of a distribution chart
            return ((_item$stats6 = item.stats) === null || _item$stats6 === void 0 ? void 0 : (_item$stats6$distribu = _item$stats6.distribution) === null || _item$stats6$distribu === void 0 ? void 0 : _item$stats6$distribu.percentiles.length) <= 2 ? /*#__PURE__*/_react.default.createElement(_top_values_preview.TopValuesPreview, {
              config: item,
              isNumeric: true
            }) : /*#__PURE__*/_react.default.createElement(_number_content_preview.IndexBasedNumberContentPreview, {
              config: item
            });
          } else {
            return /*#__PURE__*/_react.default.createElement(_field_data_row.FileBasedNumberContentPreview, {
              config: item
            });
          }
        }
        if (item.type === _constants.SUPPORTED_FIELD_TYPES.BOOLEAN) {
          return /*#__PURE__*/_react.default.createElement(_field_data_row2.BooleanContentPreview, {
            config: item
          });
        }
        return null;
      },
      width: dimensions.distributions,
      align: _eui.LEFT_ALIGNMENT,
      'data-test-subj': 'dataVisualizerTableColumnDistribution'
    }];
    return extendedColumns ? [...baseColumns, ...extendedColumns] : baseColumns;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [expandAll, showDistributions, updatePageState, extendedColumns, dimensions.breakPoint, toggleExpandAll, overallStatsRunning]);
  const itemIdToExpandedRowMap = (0, _react.useMemo)(() => {
    const itemIds = expandedRowItemIds;
    return getItemIdToExpandedRowMap(itemIds, items);
  }, [items, expandedRowItemIds, getItemIdToExpandedRowMap]);
  const $panelWidthS = `calc(max(20%, 225px))`;
  const $panelWidthM = `calc(max(30%, 300px))`;
  const dvTableCss = (0, _react2.css)({
    thead: {
      position: 'sticky',
      insetBlockStart: 0,
      zIndex: 1,
      backgroundColor: euiTheme.colors.emptyShade,
      boxShadow: `inset 0 0px 0, inset 0 -1px 0 ${euiTheme.border.color}`
    },
    '.euiTableRow > .euiTableRowCel': {
      borderTop: 0
    },
    [(0, _eui.useEuiMinBreakpoint)('s')]: {
      '& .columnHeader__title': {
        display: 'flex',
        alignItems: 'center'
      },
      '& .columnHeader__icon': {
        paddingRight: euiTheme.size.xs
      },
      '& .euiTableRow > .euiTableRowCell': {
        borderTop: 0,
        borderBottom: euiTheme.border.thin
      },
      '& .euiTableCellContent': {
        padding: euiTheme.size.xs
      },
      '& .euiTableRow-isExpandedRow': {
        '.euiTableRowCell': {
          backgroundColor: `${euiTheme.colors.emptyShade} !important`,
          borderTop: 0,
          borderBottom: euiTheme.border.thin,
          '&:hover': {
            backgroundColor: `${euiTheme.colors.emptyShade} !important`
          }
        }
      },
      '& .dvSummaryTable': {
        '.euiTableHeaderCell': {
          display: 'none'
        }
      },
      '& .dvSummaryTable__wrapper': {
        minWidth: $panelWidthS,
        maxWidth: $panelWidthS,
        '&.dvPanel__dateSummary': {
          minWidth: $panelWidthM,
          maxWidth: $panelWidthM
        }
      },
      '& .dvTopValues__wrapper': {
        minWidth: 'fit-content'
      },
      '& .dvPanel__wrapper': {
        '&.dvPanel--compressed': {
          width: $panelWidthS
        },
        '&.dvPanel--uniform': {
          minWidth: $panelWidthS,
          maxWidth: $panelWidthS
        }
      },
      '& .dvPanel__wrapper:not(:last-child)': {
        margin: `${euiTheme.size.xs} ${euiTheme.size.m} ${euiTheme.size.m} 0`
      },
      '& .dvPanel__wrapper:last-child': {
        margin: `${euiTheme.size.xs} 0 ${euiTheme.size.m} 0`
      },
      '& .dvMap__wrapper': {
        height: '240px'
      },
      '& .dvText__wrapper': {
        minWidth: $panelWidthS
      }
    }
  });
  return /*#__PURE__*/_react.default.createElement(_eui.EuiResizeObserver, {
    onResize: resizeHandler
  }, resizeRef => /*#__PURE__*/_react.default.createElement("div", {
    "data-test-subj": "dataVisualizerTableContainer",
    ref: resizeRef
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiInMemoryTable, {
    message: loading ? _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.searchingMessage', {
      defaultMessage: 'Searching'
    }) : undefined,
    css: dvTableCss,
    items: items,
    itemId: FIELD_NAME,
    columns: columns,
    pagination: pagination,
    sorting: sorting,
    isExpandable: true,
    itemIdToExpandedRowMap: itemIdToExpandedRowMap,
    isSelectable: false,
    onTableChange: onTableChange,
    "data-test-subj": `dataVisualizerTable-${loading ? 'loading' : 'loaded'}`,
    rowProps: item => ({
      'data-test-subj': `dataVisualizerRow row-${item.fieldName}`
    })
  })));
};
exports.DataVisualizerTable = DataVisualizerTable;