"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ErrorGroupDetails = ErrorGroupDetails;
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _react = _interopRequireWildcard(require("react"));
var _lodash = require("lodash");
var _reactRouterDom = require("react-router-dom");
var _agent_name = require("../../../../common/agent_name");
var _i18n2 = require("../../../../common/i18n");
var _use_apm_service_context = require("../../../context/apm_service/use_apm_service_context");
var _use_breadcrumb = require("../../../context/breadcrumbs/use_breadcrumb");
var _use_apm_params = require("../../../hooks/use_apm_params");
var _use_apm_router = require("../../../hooks/use_apm_router");
var _use_error_group_distribution_fetcher = require("../../../hooks/use_error_group_distribution_fetcher");
var _use_fetcher = require("../../../hooks/use_fetcher");
var _use_time_range = require("../../../hooks/use_time_range");
var _error_sampler = require("./error_sampler");
var _distribution = require("./distribution");
var _top_erroneous_transactions = require("./top_erroneous_transactions");
var _maybe = require("../../../../common/utils/maybe");
var _url_helpers = require("../../shared/links/url_helpers");
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 emptyErrorSamples = {
  errorSampleIds: [],
  occurrencesCount: 0
};
function getShortGroupId(errorGroupId) {
  if (!errorGroupId) {
    return _i18n2.NOT_AVAILABLE_LABEL;
  }
  return errorGroupId.slice(0, 5);
}
function ErrorGroupHeader({
  groupId,
  occurrencesCount
}) {
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h2", null, _i18n.i18n.translate('xpack.apm.errorGroupDetails.errorGroupTitle', {
    defaultMessage: 'Error group {errorGroupId}',
    values: {
      errorGroupId: getShortGroupId(groupId)
    }
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
    color: "hollow"
  }, _i18n.i18n.translate('xpack.apm.errorGroupDetails.occurrencesLabel', {
    defaultMessage: '{occurrencesCount} occ',
    values: {
      occurrencesCount
    }
  }))));
}
function ErrorGroupDetails() {
  const {
    serviceName
  } = (0, _use_apm_service_context.useApmServiceContext)();
  const apmRouter = (0, _use_apm_router.useApmRouter)();
  const history = (0, _reactRouterDom.useHistory)();
  const {
    path: {
      groupId
    },
    query: {
      rangeFrom,
      rangeTo,
      environment,
      kuery,
      serviceGroup,
      comparisonEnabled,
      errorId
    }
  } = (0, _use_apm_params.useApmParams)('/services/{serviceName}/errors/{groupId}');
  const {
    start,
    end
  } = (0, _use_time_range.useTimeRange)({
    rangeFrom,
    rangeTo
  });
  (0, _use_breadcrumb.useBreadcrumb)(() => ({
    title: groupId,
    href: apmRouter.link('/services/{serviceName}/errors/{groupId}', {
      path: {
        serviceName,
        groupId
      },
      query: {
        rangeFrom,
        rangeTo,
        environment,
        kuery,
        serviceGroup,
        comparisonEnabled
      }
    })
  }), [apmRouter, comparisonEnabled, environment, groupId, kuery, rangeFrom, rangeTo, serviceGroup, serviceName]);
  const {
    data: errorSamplesData = emptyErrorSamples,
    status: errorSamplesFetchStatus
  } = (0, _use_fetcher.useFetcher)(callApmApi => {
    if (start && end) {
      return callApmApi('GET /internal/apm/services/{serviceName}/errors/{groupId}/samples', {
        params: {
          path: {
            serviceName,
            groupId
          },
          query: {
            environment,
            kuery,
            start,
            end
          }
        }
      });
    }
  }, [environment, kuery, serviceName, start, end, groupId]);
  const {
    errorDistributionData,
    status: errorDistributionStatus
  } = (0, _use_error_group_distribution_fetcher.useErrorGroupDistributionFetcher)({
    serviceName,
    groupId,
    environment,
    kuery
  });
  (0, _react.useEffect)(() => {
    const selectedSample = errorSamplesData === null || errorSamplesData === void 0 ? void 0 : errorSamplesData.errorSampleIds.find(sample => sample === errorId);
    if (errorSamplesFetchStatus === _use_fetcher.FETCH_STATUS.SUCCESS && !selectedSample) {
      // selected sample was not found. select a new one:
      const selectedErrorId = (0, _maybe.maybe)(errorSamplesData === null || errorSamplesData === void 0 ? void 0 : errorSamplesData.errorSampleIds[0]);
      history.replace({
        ...history.location,
        search: (0, _url_helpers.fromQuery)({
          ...(0, _lodash.omit)((0, _url_helpers.toQuery)(history.location.search), ['errorId']),
          errorId: selectedErrorId
        })
      });
    }
  }, [history, errorId, errorSamplesData, errorSamplesFetchStatus]);
  const {
    agentName
  } = (0, _use_apm_service_context.useApmServiceContext)();
  const isOpenTelemetryAgent = (0, _agent_name.isOpenTelemetryAgentName)(agentName);
  const isRumAgent = (0, _agent_name.isRumAgentName)(agentName);

  // If there are 0 occurrences, show only charts w. empty message
  const showDetails = errorSamplesData.occurrencesCount !== 0;
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: 's'
  }), /*#__PURE__*/_react.default.createElement(ErrorGroupHeader, {
    groupId: groupId,
    occurrencesCount: errorSamplesData === null || errorSamplesData === void 0 ? void 0 : errorSamplesData.occurrencesCount
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: 'm'
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: 3
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    hasBorder: true
  }, /*#__PURE__*/_react.default.createElement(_distribution.ErrorDistribution, {
    fetchStatus: errorDistributionStatus,
    distribution: errorDistributionData,
    title: _i18n.i18n.translate('xpack.apm.errorGroupDetails.occurrencesChartLabel', {
      defaultMessage: 'Error occurrences'
    })
  }))), !isOpenTelemetryAgent && !isRumAgent && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: 2
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    hasBorder: true
  }, /*#__PURE__*/_react.default.createElement(_top_erroneous_transactions.TopErroneousTransactions, {
    serviceName: serviceName
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), showDetails && /*#__PURE__*/_react.default.createElement(_error_sampler.ErrorSampler, {
    errorSampleIds: errorSamplesData.errorSampleIds,
    errorSamplesFetchStatus: errorSamplesFetchStatus,
    occurrencesCount: errorSamplesData.occurrencesCount
  }));
}