"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ServiceList = ServiceList;
exports.getServiceColumns = getServiceColumns;
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _ruleDataUtils = require("@kbn/rule-data-utils");
var _react = _interopRequireWildcard(require("react"));
var _service_health_status = require("../../../../../common/service_health_status");
var _service_inventory = require("../../../../../common/service_inventory");
var _transaction_types = require("../../../../../common/transaction_types");
var _formatters = require("../../../../../common/utils/formatters");
var _use_apm_params = require("../../../../hooks/use_apm_params");
var _use_apm_router = require("../../../../hooks/use_apm_router");
var _use_breakpoints = require("../../../../hooks/use_breakpoints");
var _use_fallback_to_transactions_fetcher = require("../../../../hooks/use_fallback_to_transactions_fetcher");
var _style = require("../../../../utils/style");
var _aggregated_transactions_badge = require("../../../shared/aggregated_transactions_badge");
var _get_timeseries_color = require("../../../shared/charts/helper/get_timeseries_color");
var _environment_badge = require("../../../shared/environment_badge");
var _service_link = require("../../../shared/links/apm/service_link");
var _list_metric = require("../../../shared/list_metric");
var _managed_table = require("../../../shared/managed_table");
var _health_badge = require("./health_badge");
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.
 */

function getServiceColumns({
  query,
  showTransactionTypeColumn,
  comparisonDataLoading,
  comparisonData,
  breakpoints,
  showHealthStatusColumn,
  showAlertsColumn,
  link,
  serviceOverflowCount
}) {
  const {
    isSmall,
    isLarge,
    isXl
  } = breakpoints;
  const showWhenSmallOrGreaterThanLarge = isSmall || !isLarge;
  const showWhenSmallOrGreaterThanXL = isSmall || !isXl;
  return [...(showAlertsColumn ? [{
    field: _service_inventory.ServiceInventoryFieldName.AlertsCount,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.alertsColumnLabel', {
      defaultMessage: 'Active alerts'
    }),
    width: `${_style.unit * 8}px`,
    sortable: true,
    render: (_, {
      serviceName,
      alertsCount
    }) => {
      if (!alertsCount) {
        return null;
      }
      return /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
        position: "bottom",
        content: _i18n.i18n.translate('xpack.apm.home.servicesTable.tooltip.activeAlertsExplanation', {
          defaultMessage: 'Active alerts'
        })
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
        iconType: "warning",
        color: "danger",
        href: link('/services/{serviceName}/alerts', {
          path: {
            serviceName
          },
          query: {
            ...query,
            alertStatus: _ruleDataUtils.ALERT_STATUS_ACTIVE
          }
        })
      }, alertsCount));
    }
  }] : []), ...(showHealthStatusColumn ? [{
    field: _service_inventory.ServiceInventoryFieldName.HealthStatus,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.healthColumnLabel', {
      defaultMessage: 'Health'
    }),
    width: `${_style.unit * 6}px`,
    sortable: true,
    render: (_, {
      healthStatus
    }) => {
      return /*#__PURE__*/_react.default.createElement(_health_badge.HealthBadge, {
        healthStatus: healthStatus !== null && healthStatus !== void 0 ? healthStatus : _service_health_status.ServiceHealthStatus.unknown
      });
    }
  }] : []), {
    field: _service_inventory.ServiceInventoryFieldName.ServiceName,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.nameColumnLabel', {
      defaultMessage: 'Name'
    }),
    sortable: true,
    render: (_, {
      serviceName,
      agentName,
      transactionType
    }) => /*#__PURE__*/_react.default.createElement(_service_link.ServiceLink, {
      agentName: agentName,
      query: {
        ...query,
        transactionType
      },
      serviceName: serviceName,
      serviceOverflowCount: serviceOverflowCount
    })
  }, ...(showWhenSmallOrGreaterThanLarge ? [{
    field: _service_inventory.ServiceInventoryFieldName.Environments,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.environmentColumnLabel', {
      defaultMessage: 'Environment'
    }),
    width: `${_style.unit * 9}px`,
    sortable: true,
    render: (_, {
      environments
    }) => /*#__PURE__*/_react.default.createElement(_environment_badge.EnvironmentBadge, {
      environments: environments !== null && environments !== void 0 ? environments : []
    })
  }] : []), ...(showTransactionTypeColumn && showWhenSmallOrGreaterThanXL ? [{
    field: _service_inventory.ServiceInventoryFieldName.TransactionType,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.transactionColumnLabel', {
      defaultMessage: 'Transaction type'
    }),
    width: `${_style.unit * 8}px`,
    sortable: true
  }] : []), {
    field: _service_inventory.ServiceInventoryFieldName.Latency,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.latencyAvgColumnLabel', {
      defaultMessage: 'Latency (avg.)'
    }),
    sortable: true,
    dataType: 'number',
    render: (_, {
      serviceName,
      latency
    }) => {
      var _comparisonData$curre, _comparisonData$previ;
      const {
        currentPeriodColor,
        previousPeriodColor
      } = (0, _get_timeseries_color.getTimeSeriesColor)(_get_timeseries_color.ChartType.LATENCY_AVG);
      return /*#__PURE__*/_react.default.createElement(_list_metric.ListMetric, {
        isLoading: comparisonDataLoading,
        series: comparisonData === null || comparisonData === void 0 ? void 0 : (_comparisonData$curre = comparisonData.currentPeriod[serviceName]) === null || _comparisonData$curre === void 0 ? void 0 : _comparisonData$curre.latency,
        comparisonSeries: comparisonData === null || comparisonData === void 0 ? void 0 : (_comparisonData$previ = comparisonData.previousPeriod[serviceName]) === null || _comparisonData$previ === void 0 ? void 0 : _comparisonData$previ.latency,
        hideSeries: !showWhenSmallOrGreaterThanLarge,
        color: currentPeriodColor,
        valueLabel: (0, _formatters.asMillisecondDuration)(latency || 0),
        comparisonSeriesColor: previousPeriodColor
      });
    },
    align: _eui.RIGHT_ALIGNMENT
  }, {
    field: _service_inventory.ServiceInventoryFieldName.Throughput,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.throughputColumnLabel', {
      defaultMessage: 'Throughput'
    }),
    sortable: true,
    dataType: 'number',
    render: (_, {
      serviceName,
      throughput
    }) => {
      var _comparisonData$curre2, _comparisonData$previ2;
      const {
        currentPeriodColor,
        previousPeriodColor
      } = (0, _get_timeseries_color.getTimeSeriesColor)(_get_timeseries_color.ChartType.THROUGHPUT);
      return /*#__PURE__*/_react.default.createElement(_list_metric.ListMetric, {
        isLoading: comparisonDataLoading,
        series: comparisonData === null || comparisonData === void 0 ? void 0 : (_comparisonData$curre2 = comparisonData.currentPeriod[serviceName]) === null || _comparisonData$curre2 === void 0 ? void 0 : _comparisonData$curre2.throughput,
        comparisonSeries: comparisonData === null || comparisonData === void 0 ? void 0 : (_comparisonData$previ2 = comparisonData.previousPeriod[serviceName]) === null || _comparisonData$previ2 === void 0 ? void 0 : _comparisonData$previ2.throughput,
        hideSeries: !showWhenSmallOrGreaterThanLarge,
        color: currentPeriodColor,
        valueLabel: (0, _formatters.asTransactionRate)(throughput),
        comparisonSeriesColor: previousPeriodColor
      });
    },
    align: _eui.RIGHT_ALIGNMENT
  }, {
    field: _service_inventory.ServiceInventoryFieldName.TransactionErrorRate,
    name: _i18n.i18n.translate('xpack.apm.servicesTable.transactionErrorRate', {
      defaultMessage: 'Failed transaction rate'
    }),
    sortable: true,
    dataType: 'number',
    render: (_, {
      serviceName,
      transactionErrorRate
    }) => {
      var _comparisonData$curre3, _comparisonData$previ3;
      const valueLabel = (0, _formatters.asPercent)(transactionErrorRate, 1);
      const {
        currentPeriodColor,
        previousPeriodColor
      } = (0, _get_timeseries_color.getTimeSeriesColor)(_get_timeseries_color.ChartType.FAILED_TRANSACTION_RATE);
      return /*#__PURE__*/_react.default.createElement(_list_metric.ListMetric, {
        isLoading: comparisonDataLoading,
        series: comparisonData === null || comparisonData === void 0 ? void 0 : (_comparisonData$curre3 = comparisonData.currentPeriod[serviceName]) === null || _comparisonData$curre3 === void 0 ? void 0 : _comparisonData$curre3.transactionErrorRate,
        comparisonSeries: comparisonData === null || comparisonData === void 0 ? void 0 : (_comparisonData$previ3 = comparisonData.previousPeriod[serviceName]) === null || _comparisonData$previ3 === void 0 ? void 0 : _comparisonData$previ3.transactionErrorRate,
        hideSeries: !showWhenSmallOrGreaterThanLarge,
        color: currentPeriodColor,
        valueLabel: valueLabel,
        comparisonSeriesColor: previousPeriodColor
      });
    },
    align: _eui.RIGHT_ALIGNMENT
  }];
}
function ServiceList({
  items,
  noItemsMessage,
  comparisonDataLoading,
  comparisonData,
  isLoading,
  isFailure,
  displayHealthStatus,
  displayAlerts,
  initialSortField,
  initialSortDirection,
  initialPageSize,
  sortFn,
  serviceOverflowCount
}) {
  const breakpoints = (0, _use_breakpoints.useBreakpoints)();
  const {
    link
  } = (0, _use_apm_router.useApmRouter)();
  const showTransactionTypeColumn = items.some(({
    transactionType
  }) => transactionType && !(0, _transaction_types.isDefaultTransactionType)(transactionType));
  const {
    // removes pagination and sort instructions from the query so it won't be passed down to next route
    query: {
      page,
      pageSize,
      sortDirection: direction,
      sortField: field,
      ...query
    }
  } = (0, _use_apm_params.useApmParams)('/services');
  const {
    kuery
  } = query;
  const {
    fallbackToTransactions
  } = (0, _use_fallback_to_transactions_fetcher.useFallbackToTransactionsFetcher)({
    kuery
  });
  const serviceColumns = (0, _react.useMemo)(() => getServiceColumns({
    query,
    showTransactionTypeColumn,
    comparisonDataLoading,
    comparisonData,
    breakpoints,
    showHealthStatusColumn: displayHealthStatus,
    showAlertsColumn: displayAlerts,
    link,
    serviceOverflowCount
  }), [query, showTransactionTypeColumn, comparisonDataLoading, comparisonData, breakpoints, displayHealthStatus, displayAlerts, link, serviceOverflowCount]);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "xs",
    direction: "column",
    responsive: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center",
    gutterSize: "xs",
    justifyContent: "flexEnd"
  }, fallbackToTransactions && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_aggregated_transactions_badge.AggregatedTransactionsBadge, null)), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
    position: "top",
    content: _i18n.i18n.translate('xpack.apm.servicesTable.tooltip.metricsExplanation', {
      defaultMessage: 'Service metrics are aggregated on their transaction type, which can be request or page-load. If neither exists, metrics are aggregated on the top available transaction type.'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    type: "questionInCircle",
    color: "subdued"
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    size: "xs",
    color: "subdued"
  }, _i18n.i18n.translate('xpack.apm.servicesTable.metricsExplanationLabel', {
    defaultMessage: 'What are these metrics?'
  }))))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_managed_table.ManagedTable, {
    isLoading: isLoading,
    error: isFailure,
    columns: serviceColumns,
    items: items,
    noItemsMessage: noItemsMessage,
    initialSortField: initialSortField,
    initialSortDirection: initialSortDirection,
    initialPageSize: initialPageSize,
    sortFn: (itemsToSort, sortField, sortDirection) => sortFn(itemsToSort, sortField, sortDirection)
  })));
}