"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FailedTransactionRateChart = FailedTransactionRateChart;
exports.errorRateI18n = void 0;
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _react = _interopRequireDefault(require("react"));
var _use_previous_period_text = require("../../../../hooks/use_previous_period_text");
var _get_comparison_options = require("../../time_comparison/get_comparison_options");
var _formatters = require("../../../../../common/utils/formatters");
var _use_fetcher = require("../../../../hooks/use_fetcher");
var _use_url_params = require("../../../../context/url_params_context/use_url_params");
var _timeseries_chart_with_context = require("../timeseries_chart_with_context");
var _use_apm_service_context = require("../../../../context/apm_service/use_apm_service_context");
var _get_comparison_chart_theme = require("../../time_comparison/get_comparison_chart_theme");
var _use_apm_params = require("../../../../hooks/use_apm_params");
var _use_time_range = require("../../../../hooks/use_time_range");
var _use_environments_context = require("../../../../context/environments_context/use_environments_context");
var _apm_ml_detectors = require("../../../../../common/anomaly_detection/apm_ml_detectors");
var _use_preferred_service_anomaly_timeseries = require("../../../../hooks/use_preferred_service_anomaly_timeseries");
var _get_timeseries_color = require("../helper/get_timeseries_color");
var _use_preferred_data_source_and_bucket_size = require("../../../../hooks/use_preferred_data_source_and_bucket_size");
var _document_type = require("../../../../../common/document_type");
/*
 * 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 yLabelFormat(y) {
  return (0, _formatters.asPercent)(y || 0, 1);
}
const INITIAL_STATE = {
  currentPeriod: {
    timeseries: [],
    average: null
  },
  previousPeriod: {
    timeseries: [],
    average: null
  }
};
const errorRateI18n = _i18n.i18n.translate('xpack.apm.errorRate.tip', {
  defaultMessage: "The percentage of failed transactions for the selected service. HTTP server transactions with a 4xx status code (client error) aren't considered failures because the caller, not the server, caused the failure."
});
exports.errorRateI18n = errorRateI18n;
function FailedTransactionRateChart({
  height,
  showAnnotations = true,
  kuery
}) {
  var _data$currentPeriod$t, _data$currentPeriod, _data$previousPeriod$, _data$previousPeriod;
  const {
    urlParams: {
      transactionName
    }
  } = (0, _use_url_params.useLegacyUrlParams)();
  const {
    query: {
      rangeFrom,
      rangeTo,
      comparisonEnabled,
      offset
    }
  } = (0, _use_apm_params.useAnyOfApmParams)('/services/{serviceName}', '/mobile-services/{serviceName}');
  const {
    start,
    end
  } = (0, _use_time_range.useTimeRange)({
    rangeFrom,
    rangeTo
  });
  const preferred = (0, _use_preferred_data_source_and_bucket_size.usePreferredDataSourceAndBucketSize)({
    start,
    end,
    numBuckets: 100,
    kuery,
    type: transactionName ? _document_type.ApmDocumentType.TransactionMetric : _document_type.ApmDocumentType.ServiceTransactionMetric
  });
  const {
    environment
  } = (0, _use_environments_context.useEnvironmentsContext)();
  const preferredAnomalyTimeseries = (0, _use_preferred_service_anomaly_timeseries.usePreferredServiceAnomalyTimeseries)(_apm_ml_detectors.ApmMlDetectorType.txFailureRate);
  const {
    serviceName,
    transactionType,
    transactionTypeStatus
  } = (0, _use_apm_service_context.useApmServiceContext)();
  const comparisonChartTheme = (0, _get_comparison_chart_theme.getComparisonChartTheme)();
  const {
    data = INITIAL_STATE,
    status
  } = (0, _use_fetcher.useFetcher)(callApmApi => {
    if (!transactionType && transactionTypeStatus === _use_fetcher.FETCH_STATUS.SUCCESS) {
      return Promise.resolve(INITIAL_STATE);
    }
    if (transactionType && serviceName && start && end && preferred) {
      return callApmApi('GET /internal/apm/services/{serviceName}/transactions/charts/error_rate', {
        params: {
          path: {
            serviceName
          },
          query: {
            environment,
            kuery,
            start,
            end,
            transactionType,
            transactionName,
            offset: comparisonEnabled && (0, _get_comparison_options.isTimeComparison)(offset) ? offset : undefined,
            documentType: preferred.source.documentType,
            rollupInterval: preferred.source.rollupInterval,
            bucketSizeInSeconds: preferred.bucketSizeInSeconds
          }
        }
      });
    }
  }, [environment, kuery, serviceName, start, end, transactionType, transactionTypeStatus, transactionName, offset, comparisonEnabled, preferred]);
  const {
    currentPeriodColor,
    previousPeriodColor
  } = (0, _get_timeseries_color.getTimeSeriesColor)(_get_timeseries_color.ChartType.FAILED_TRANSACTION_RATE);
  const previousPeriodLabel = (0, _use_previous_period_text.usePreviousPeriodLabel)();
  const timeseries = [{
    data: (_data$currentPeriod$t = data === null || data === void 0 ? void 0 : (_data$currentPeriod = data.currentPeriod) === null || _data$currentPeriod === void 0 ? void 0 : _data$currentPeriod.timeseries) !== null && _data$currentPeriod$t !== void 0 ? _data$currentPeriod$t : [],
    type: 'linemark',
    color: currentPeriodColor,
    title: _i18n.i18n.translate('xpack.apm.errorRate.chart.errorRate', {
      defaultMessage: 'Failed transaction rate (avg.)'
    })
  }, ...(comparisonEnabled ? [{
    data: (_data$previousPeriod$ = data === null || data === void 0 ? void 0 : (_data$previousPeriod = data.previousPeriod) === null || _data$previousPeriod === void 0 ? void 0 : _data$previousPeriod.timeseries) !== null && _data$previousPeriod$ !== void 0 ? _data$previousPeriod$ : [],
    type: 'area',
    color: previousPeriodColor,
    title: previousPeriodLabel
  }] : [])];
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    hasBorder: true
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center",
    gutterSize: "s",
    responsive: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "xs"
  }, /*#__PURE__*/_react.default.createElement("h2", null, _i18n.i18n.translate('xpack.apm.errorRate', {
    defaultMessage: 'Failed transaction rate'
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiIconTip, {
    content: errorRateI18n,
    position: "right"
  }))), /*#__PURE__*/_react.default.createElement(_timeseries_chart_with_context.TimeseriesChartWithContext, {
    id: "errorRate",
    height: height,
    showAnnotations: showAnnotations,
    fetchStatus: status,
    timeseries: timeseries,
    yLabelFormat: yLabelFormat,
    yDomain: {
      min: 0,
      max: 1
    },
    customTheme: comparisonChartTheme,
    anomalyTimeseries: preferredAnomalyTimeseries ? {
      ...preferredAnomalyTimeseries,
      color: previousPeriodColor
    } : undefined
  }));
}