"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FieldStatisticsTable = void 0;
var _react = _interopRequireWildcard(require("react"));
var _analytics = require("@kbn/analytics");
var _public = require("@kbn/embeddable-plugin/public");
var _eui = require("@elastic/eui");
var _react2 = require("@emotion/react");
var _use_discover_services = require("../../../../hooks/use_discover_services");
var _constants = require("./constants");
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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const FieldStatisticsTable = props => {
  const {
    dataView,
    savedSearch,
    query,
    columns,
    filters,
    stateContainer,
    onAddFilter,
    trackUiMetric,
    searchSessionId
  } = props;
  const totalHits$ = stateContainer === null || stateContainer === void 0 ? void 0 : stateContainer.dataState.data$.totalHits$;
  const services = (0, _use_discover_services.useDiscoverServices)();
  const [embeddable, setEmbeddable] = (0, _react.useState)();
  const embeddableRoot = (0, _react.useRef)(null);
  const showPreviewByDefault = (0, _react.useMemo)(() => stateContainer ? !stateContainer.appState.getState().hideAggregatedPreview : true, [stateContainer]);
  (0, _react.useEffect)(() => {
    const availableFields$ = stateContainer === null || stateContainer === void 0 ? void 0 : stateContainer.dataState.data$.availableFields$;
    const sub = embeddable === null || embeddable === void 0 ? void 0 : embeddable.getOutput$().subscribe(output => {
      if (output.showDistributions !== undefined && stateContainer) {
        stateContainer.appState.update({
          hideAggregatedPreview: !output.showDistributions
        });
      }
    });
    const refetch = stateContainer === null || stateContainer === void 0 ? void 0 : stateContainer.dataState.refetch$.subscribe(() => {
      if (embeddable && !(0, _public.isErrorEmbeddable)(embeddable)) {
        embeddable.updateInput({
          lastReloadRequestTime: Date.now()
        });
      }
    });
    const fields = availableFields$ === null || availableFields$ === void 0 ? void 0 : availableFields$.subscribe(() => {
      if (embeddable && !(0, _public.isErrorEmbeddable)(embeddable) && !(availableFields$ !== null && availableFields$ !== void 0 && availableFields$.getValue().error)) {
        embeddable.updateInput({
          fieldsToFetch: availableFields$ === null || availableFields$ === void 0 ? void 0 : availableFields$.getValue().fields
        });
      }
    });
    return () => {
      sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
      refetch === null || refetch === void 0 ? void 0 : refetch.unsubscribe();
      fields === null || fields === void 0 ? void 0 : fields.unsubscribe();
    };
  }, [embeddable, stateContainer]);
  (0, _react.useEffect)(() => {
    if (embeddable && !(0, _public.isErrorEmbeddable)(embeddable)) {
      var _stateContainer$dataS, _totalHits$$getValue;
      // Update embeddable whenever one of the important input changes
      embeddable.updateInput({
        dataView,
        savedSearch,
        query,
        filters,
        visibleFieldNames: columns,
        onAddFilter,
        sessionId: searchSessionId,
        fieldsToFetch: stateContainer === null || stateContainer === void 0 ? void 0 : (_stateContainer$dataS = stateContainer.dataState.data$.availableFields$) === null || _stateContainer$dataS === void 0 ? void 0 : _stateContainer$dataS.getValue().fields,
        totalDocuments: totalHits$ ? (_totalHits$$getValue = totalHits$.getValue()) === null || _totalHits$$getValue === void 0 ? void 0 : _totalHits$$getValue.result : undefined,
        samplingOption: {
          mode: 'normal_sampling',
          shardSize: 5000,
          seed: searchSessionId
        }
      });
      embeddable.reload();
    }
  }, [embeddable, dataView, savedSearch, query, columns, filters, onAddFilter, searchSessionId, totalHits$, stateContainer]);
  (0, _react.useEffect)(() => {
    if (showPreviewByDefault && embeddable && !(0, _public.isErrorEmbeddable)(embeddable)) {
      // Update embeddable whenever one of the important input changes
      embeddable.updateInput({
        showPreviewByDefault
      });
      embeddable.reload();
    }
  }, [showPreviewByDefault, embeddable]);
  (0, _react.useEffect)(() => {
    let unmounted = false;
    const loadEmbeddable = async () => {
      if (services.embeddable) {
        const factory = services.embeddable.getEmbeddableFactory('data_visualizer_grid');
        if (factory) {
          // Initialize embeddable with information available at mount
          const initializedEmbeddable = await factory.create({
            id: 'discover_data_visualizer_grid',
            dataView,
            savedSearch,
            query,
            showPreviewByDefault,
            onAddFilter
          });
          if (!unmounted) {
            setEmbeddable(initializedEmbeddable);
          }
        }
      }
    };
    loadEmbeddable();
    return () => {
      unmounted = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [services.embeddable, showPreviewByDefault]);

  // We can only render after embeddable has already initialized
  (0, _react.useEffect)(() => {
    if (embeddableRoot.current && embeddable) {
      embeddable.render(embeddableRoot.current);
      trackUiMetric === null || trackUiMetric === void 0 ? void 0 : trackUiMetric(_analytics.METRIC_TYPE.LOADED, _constants.FIELD_STATISTICS_LOADED);
    }
    return () => {
      // Clean up embeddable upon unmounting
      embeddable === null || embeddable === void 0 ? void 0 : embeddable.destroy();
    };
  }, [embeddable, embeddableRoot, trackUiMetric]);
  const statsTableCss = (0, _react2.css)`
    overflow-y: auto;

    .kbnDocTableWrapper {
      overflow-x: hidden;
    }
  `;
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    css: statsTableCss
  }, /*#__PURE__*/_react.default.createElement("div", {
    "data-test-subj": "dscFieldStatsEmbeddedContent",
    ref: embeddableRoot
    // Match the scroll bar of the Discover doc table
    ,
    className: "kbnDocTableWrapper"
  }));
};
exports.FieldStatisticsTable = FieldStatisticsTable;