"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ServicesTable = ServicesTable;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _public = require("@kbn/kibana-react-plugin/public");
var _common = require("@kbn/observability-plugin/common");
var _moment = _interopRequireDefault(require("moment"));
var _lodash = require("lodash");
var _download_json = require("../../../../utils/download_json");
var _environment_badge = require("../../../shared/environment_badge");
var _formatters = require("../../../../../common/utils/formatters");
var _service_link = require("../../../shared/links/apm/service_link");
var _truncate_with_tooltip = require("../../../shared/truncate_with_tooltip");
var _storage_details_per_service = require("./storage_details_per_service");
var _get_comparison_enabled = require("../../../shared/time_comparison/get_comparison_enabled");
var _use_apm_plugin_context = require("../../../../context/apm_plugin/use_apm_plugin_context");
var _i18n2 = require("../../../../../common/i18n");
var _use_apm_params = require("../../../../hooks/use_apm_params");
var _use_fetcher = require("../../../../hooks/use_fetcher");
var _use_progressive_fetcher = require("../../../../hooks/use_progressive_fetcher");
var _use_time_range = require("../../../../hooks/use_time_range");
var _size_label = require("./size_label");
var _join_by_key = require("../../../../../common/utils/join_by_key");
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.
 */
var StorageExplorerFieldName;
(function (StorageExplorerFieldName) {
  StorageExplorerFieldName["ServiceName"] = "serviceName";
  StorageExplorerFieldName["Environments"] = "environments";
  StorageExplorerFieldName["Sampling"] = "sampling";
  StorageExplorerFieldName["Size"] = "size";
})(StorageExplorerFieldName || (StorageExplorerFieldName = {}));
function ServicesTable({
  summaryStatsData,
  loadingSummaryStats
}) {
  var _useKibana$services$u, _serviceStatisticsFet, _serviceStatisticsFet2, _sortedAndFilteredSer;
  const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = (0, _react.useState)({});
  const {
    core
  } = (0, _use_apm_plugin_context.useApmPluginContext)();
  const {
    query: {
      rangeFrom,
      rangeTo,
      environment,
      kuery,
      indexLifecyclePhase,
      comparisonEnabled: urlComparisonEnabled
    }
  } = (0, _use_apm_params.useApmParams)('/storage-explorer');
  const {
    start,
    end
  } = (0, _use_time_range.useTimeRange)({
    rangeFrom,
    rangeTo
  });
  const comparisonEnabled = (0, _get_comparison_enabled.getComparisonEnabled)({
    core,
    urlComparisonEnabled
  });
  const toggleRowDetails = selectedServiceName => {
    const expandedRowMapValues = {
      ...itemIdToExpandedRowMap
    };
    if (expandedRowMapValues[selectedServiceName]) {
      delete expandedRowMapValues[selectedServiceName];
    } else {
      expandedRowMapValues[selectedServiceName] = /*#__PURE__*/_react.default.createElement(_storage_details_per_service.StorageDetailsPerService, {
        serviceName: selectedServiceName,
        indexLifecyclePhase: indexLifecyclePhase
      });
    }
    setItemIdToExpandedRowMap(expandedRowMapValues);
  };
  const useOptimizedSorting = ((_useKibana$services$u = (0, _public.useKibana)().services.uiSettings) === null || _useKibana$services$u === void 0 ? void 0 : _useKibana$services$u.get(_common.apmServiceInventoryOptimizedSorting)) || false;
  const sortedAndFilteredServicesFetch = (0, _use_fetcher.useFetcher)(callApmApi => {
    if (useOptimizedSorting) {
      return callApmApi('GET /internal/apm/storage_explorer/get_services', {
        params: {
          query: {
            environment,
            kuery,
            indexLifecyclePhase,
            start,
            end
          }
        }
      });
    }
  }, [useOptimizedSorting, environment, kuery, indexLifecyclePhase, start, end]);
  const serviceStatisticsFetch = (0, _use_progressive_fetcher.useProgressiveFetcher)(callApmApi => {
    return callApmApi('GET /internal/apm/storage_explorer', {
      params: {
        query: {
          indexLifecyclePhase,
          start,
          end,
          environment,
          kuery
        }
      }
    });
  }, [indexLifecyclePhase, start, end, environment, kuery]);
  const serviceStatisticsItems = (_serviceStatisticsFet = (_serviceStatisticsFet2 = serviceStatisticsFetch.data) === null || _serviceStatisticsFet2 === void 0 ? void 0 : _serviceStatisticsFet2.serviceStatistics) !== null && _serviceStatisticsFet !== void 0 ? _serviceStatisticsFet : [];
  const preloadedServices = ((_sortedAndFilteredSer = sortedAndFilteredServicesFetch.data) === null || _sortedAndFilteredSer === void 0 ? void 0 : _sortedAndFilteredSer.services) || [];
  const initialSortField = useOptimizedSorting ? StorageExplorerFieldName.ServiceName : StorageExplorerFieldName.Size;
  const initialSortDirection = initialSortField === StorageExplorerFieldName.ServiceName ? 'asc' : 'desc';
  const loading = serviceStatisticsFetch.status === _use_fetcher.FETCH_STATUS.LOADING;
  const items = (0, _join_by_key.joinByKey)([...(initialSortField === StorageExplorerFieldName.ServiceName ? preloadedServices : []), ...serviceStatisticsItems], 'serviceName');
  const columns = [{
    field: 'serviceName',
    name: _i18n.i18n.translate('xpack.apm.storageExplorer.table.serviceColumnName', {
      defaultMessage: 'Service'
    }),
    sortable: true,
    render: (_, {
      serviceName,
      agentName
    }) => {
      const serviceLinkQuery = {
        comparisonEnabled,
        environment,
        kuery,
        rangeFrom,
        rangeTo,
        serviceGroup: ''
      };
      return /*#__PURE__*/_react.default.createElement(_truncate_with_tooltip.TruncateWithTooltip, {
        "data-test-subj": "apmStorageExplorerServiceLink",
        text: serviceName || _i18n2.NOT_AVAILABLE_LABEL,
        content: /*#__PURE__*/_react.default.createElement(_service_link.ServiceLink, {
          query: serviceLinkQuery,
          serviceName: serviceName,
          agentName: agentName
        })
      });
    }
  }, {
    field: 'environment',
    name: _i18n.i18n.translate('xpack.apm.storageExplorer.table.environmentColumnName', {
      defaultMessage: 'Environment'
    }),
    render: (_, {
      environments
    }) => /*#__PURE__*/_react.default.createElement(_environment_badge.EnvironmentBadge, {
      environments: environments !== null && environments !== void 0 ? environments : []
    }),
    sortable: true
  }, {
    field: 'sampling',
    name: /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
      content: _i18n.i18n.translate('xpack.apm.storageExplorer.table.samplingColumnDescription', {
        defaultMessage: `The number of sampled transactions divided by total throughput. This value may differ from the configured transaction sample rate because it might be affected by the initial service's decision when using head-based sampling or by a set of policies when using tail-based sampling.`
      })
    }, /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, _i18n.i18n.translate('xpack.apm.storageExplorer.table.samplingColumnName', {
      defaultMessage: 'Sampling rate'
    }), ' ', /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      size: "s",
      color: "subdued",
      type: "questionInCircle",
      className: "eui-alignTop"
    }))),
    render: value => (0, _formatters.asPercent)(parseFloat(value), 1),
    sortable: true
  }, {
    field: 'size',
    name: /*#__PURE__*/_react.default.createElement(_size_label.SizeLabel, null),
    render: (_, {
      size
    }) => (0, _formatters.asDynamicBytes)(size) || _i18n2.NOT_AVAILABLE_LABEL,
    sortable: true
  }, {
    align: _eui.RIGHT_ALIGNMENT,
    width: '40px',
    isExpander: true,
    name: /*#__PURE__*/_react.default.createElement(_eui.EuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("span", null, _i18n.i18n.translate('xpack.apm.storageExplorer.table.expandRow', {
      defaultMessage: 'Expand row'
    }))),
    render: ({
      serviceName
    }) => {
      return /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
        "data-test-subj": `storageDetailsButton_${serviceName}`,
        onClick: () => toggleRowDetails(serviceName),
        "aria-label": itemIdToExpandedRowMap[serviceName] ? _i18n.i18n.translate('xpack.apm.storageExplorer.table.collapse', {
          defaultMessage: 'Collapse'
        }) : _i18n.i18n.translate('xpack.apm.storageExplorer.table.expand', {
          defaultMessage: 'Expand'
        }),
        iconType: itemIdToExpandedRowMap[serviceName] ? 'arrowUp' : 'arrowDown'
      });
    }
  }];
  const isDownloadButtonDisable = (0, _lodash.isEmpty)(serviceStatisticsItems) || loadingSummaryStats;
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    hasShadow: false,
    paddingSize: "none",
    style: {
      position: 'relative'
    }
  }, loading && /*#__PURE__*/_react.default.createElement(_eui.EuiProgress, {
    size: "xs",
    color: "accent",
    position: "absolute"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    justifyContent: "flexEnd"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    "data-test-subj": "StorageExplorerDownloadReportButton",
    iconType: "download",
    isDisabled: isDownloadButtonDisable,
    onClick: () => {
      var _summaryStatsData$num;
      return (0, _download_json.downloadJson)({
        fileName: `storage-explorefpr-${(0, _moment.default)(Date.now()).format('YYYYMMDDHHmmss')}.json`,
        data: {
          filters: {
            rangeFrom,
            rangeTo,
            environment,
            kuery,
            indexLifecyclePhase
          },
          summary: {
            totalSize: (0, _formatters.asDynamicBytes)(summaryStatsData === null || summaryStatsData === void 0 ? void 0 : summaryStatsData.totalSize),
            diskSpaceUsedPct: (0, _formatters.asPercent)(summaryStatsData === null || summaryStatsData === void 0 ? void 0 : summaryStatsData.diskSpaceUsedPct, 1),
            estimatedIncrementalSize: (0, _formatters.asDynamicBytes)(summaryStatsData === null || summaryStatsData === void 0 ? void 0 : summaryStatsData.estimatedIncrementalSize),
            dailyDataGeneration: (0, _formatters.asDynamicBytes)(summaryStatsData === null || summaryStatsData === void 0 ? void 0 : summaryStatsData.dailyDataGeneration),
            tracesPerMinute: (0, _formatters.asTransactionRate)(summaryStatsData === null || summaryStatsData === void 0 ? void 0 : summaryStatsData.tracesPerMinute),
            numberOfServices: ((_summaryStatsData$num = summaryStatsData === null || summaryStatsData === void 0 ? void 0 : summaryStatsData.numberOfServices) !== null && _summaryStatsData$num !== void 0 ? _summaryStatsData$num : 0).toString()
          },
          services: serviceStatisticsItems.map(item => ({
            ...item,
            sampling: (0, _formatters.asPercent)(item === null || item === void 0 ? void 0 : item.sampling, 1),
            size: item !== null && item !== void 0 && item.size ? (0, _formatters.asDynamicBytes)(item === null || item === void 0 ? void 0 : item.size) : _i18n2.NOT_AVAILABLE_LABEL
          }))
        }
      });
    },
    fill: true
  }, _i18n.i18n.translate('xpack.apm.storageExplorer.downloadReport', {
    defaultMessage: 'Download report'
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiInMemoryTable, {
    tableCaption: _i18n.i18n.translate('xpack.apm.storageExplorer.table.caption', {
      defaultMessage: 'Storage Explorer'
    }),
    items: items !== null && items !== void 0 ? items : [],
    columns: columns,
    pagination: true,
    sorting: {
      sort: {
        field: initialSortField,
        direction: initialSortDirection
      }
    },
    itemId: "serviceName",
    itemIdToExpandedRowMap: itemIdToExpandedRowMap,
    "data-test-subj": "storageExplorerServicesTable",
    error: status === _use_fetcher.FETCH_STATUS.FAILURE ? _i18n.i18n.translate('xpack.apm.storageExplorer.table.errorMessage', {
      defaultMessage: 'Failed to fetch'
    }) : '',
    message: loading ? _i18n.i18n.translate('xpack.apm.storageExplorer.table.loading', {
      defaultMessage: 'Loading...'
    }) : _i18n.i18n.translate('xpack.apm.storageExplorer.table.noResults', {
      defaultMessage: 'No data found'
    })
  }));
}