"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ErrorSampleDetailTabContent = ErrorSampleDetailTabContent;
exports.ErrorSampleDetails = ErrorSampleDetails;
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _common = require("@kbn/kibana-react-plugin/common");
var _common2 = require("@kbn/observability-shared-plugin/common");
var _public = require("@kbn/observability-shared-plugin/public");
var _lodash = require("lodash");
var _react = _interopRequireWildcard(require("react"));
var _reactRouterDom = require("react-router-dom");
var _useAsync = _interopRequireDefault(require("react-use/lib/useAsync"));
var _apm = require("../../../../../common/es_fields/apm");
var _trace_explorer = require("../../../../../common/trace_explorer");
var _use_apm_plugin_context = require("../../../../context/apm_plugin/use_apm_plugin_context");
var _use_url_params = require("../../../../context/url_params_context/use_url_params");
var _use_apm_params = require("../../../../hooks/use_apm_params");
var _use_apm_router = require("../../../../hooks/use_apm_router");
var _use_fetcher = require("../../../../hooks/use_fetcher");
var _use_trace_explorer_enabled_setting = require("../../../../hooks/use_trace_explorer_enabled_setting");
var _transaction_detail_link = require("../../../shared/links/apm/transaction_detail_link");
var _discover_error_link = require("../../../shared/links/discover_links/discover_error_link");
var _url_helpers = require("../../../shared/links/url_helpers");
var _error_metadata = require("../../../shared/metadata_table/error_metadata");
var _stacktrace = require("../../../shared/stacktrace");
var _summary = require("../../../shared/summary");
var _http_info_summary_item = require("../../../shared/summary/http_info_summary_item");
var _user_agent_summary_item = require("../../../shared/summary/user_agent_summary_item");
var _timestamp_tooltip = require("../../../shared/timestamp_tooltip");
var _plaintext_stacktrace = require("./plaintext_stacktrace");
var _transaction_tabs = require("../../transaction_details/waterfall_with_summary/transaction_tabs");
var _error_tabs = require("./error_tabs");
var _error_ui_actions_context_menu = require("./error_ui_actions_context_menu");
var _exception_stacktrace = require("./exception_stacktrace");
var _sample_summary = require("./sample_summary");
var _error_sample_contextual_insight = require("./error_sample_contextual_insight");
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 TransactionLinkName = _common.euiStyled.div`
  margin-left: ${({
  theme
}) => theme.eui.euiSizeS};
  display: inline-block;
  vertical-align: middle;
`;
function getCurrentTab(tabs = [], currentTabKey) {
  const selectedTab = tabs.find(({
    key
  }) => key === currentTabKey);
  return selectedTab !== null && selectedTab !== void 0 ? selectedTab : (0, _lodash.first)(tabs) || {};
}
function ErrorSampleDetails({
  onSampleClick,
  errorSampleIds,
  errorSamplesFetchStatus,
  errorData,
  errorFetchStatus,
  occurrencesCount
}) {
  var _error$error$page, _error$url, _error$http, _error$http$request, _error$http2, _error$http2$response, _error$error$exceptio, _externalContextMenuI;
  const [sampleActivePage, setSampleActivePage] = (0, _react.useState)(0);
  const history = (0, _reactRouterDom.useHistory)();
  const {
    urlParams: {
      detailTab,
      offset,
      comparisonEnabled
    }
  } = (0, _use_url_params.useLegacyUrlParams)();
  const {
    uiActions
  } = (0, _use_apm_plugin_context.useApmPluginContext)();
  const router = (0, _use_apm_router.useApmRouter)();
  const isTraceExplorerEnabled = (0, _use_trace_explorer_enabled_setting.useTraceExplorerEnabledSetting)();
  const {
    path: {
      groupId
    },
    query
  } = (0, _use_apm_params.useApmParams)('/services/{serviceName}/errors/{groupId}');
  const {
    kuery
  } = query;
  const loadingErrorSamplesData = (0, _use_fetcher.isPending)(errorSamplesFetchStatus);
  const loadingErrorData = (0, _use_fetcher.isPending)(errorFetchStatus);
  const isLoading = loadingErrorSamplesData || loadingErrorData;
  const isSucceded = errorSamplesFetchStatus === _use_fetcher.FETCH_STATUS.SUCCESS && errorFetchStatus === _use_fetcher.FETCH_STATUS.SUCCESS;
  (0, _react.useEffect)(() => {
    setSampleActivePage(0);
  }, [errorSampleIds]);
  const goToSample = index => {
    const sample = errorSampleIds[index];
    setSampleActivePage(index);
    onSampleClick(sample);
  };
  const {
    error,
    transaction
  } = errorData;
  const externalContextMenuItems = (0, _useAsync.default)(() => {
    return (0, _public.getContextMenuItemsFromActions)({
      uiActions,
      triggerId: _common2.ObservabilityTriggerId.ApmErrorContextMenu,
      context: {
        error,
        transaction
      }
    });
  }, [error, transaction, uiActions]);
  if (!error && (errorSampleIds === null || errorSampleIds === void 0 ? void 0 : errorSampleIds.length) === 0 && isSucceded) {
    return /*#__PURE__*/_react.default.createElement(_eui.EuiEmptyPrompt, {
      title: /*#__PURE__*/_react.default.createElement("div", null, _i18n.i18n.translate('xpack.apm.errorSampleDetails.sampleNotFound', {
        defaultMessage: 'The selected error cannot be found'
      })),
      titleSize: "s"
    });
  }
  const tabs = (0, _error_tabs.getTabs)(error);
  const currentTab = getCurrentTab(tabs, detailTab);
  const errorUrl = ((_error$error$page = error.error.page) === null || _error$error$page === void 0 ? void 0 : _error$error$page.url) || ((_error$url = error.url) === null || _error$url === void 0 ? void 0 : _error$url.full);
  const method = (_error$http = error.http) === null || _error$http === void 0 ? void 0 : (_error$http$request = _error$http.request) === null || _error$http$request === void 0 ? void 0 : _error$http$request.method;
  const status = (_error$http2 = error.http) === null || _error$http2 === void 0 ? void 0 : (_error$http2$response = _error$http2.response) === null || _error$http2$response === void 0 ? void 0 : _error$http2$response.status_code;
  const environment = error.service.environment;
  const serviceVersion = error.service.version;
  const isUnhandled = ((_error$error$exceptio = error.error.exception) === null || _error$error$exceptio === void 0 ? void 0 : _error$error$exceptio[0].handled) === false;
  const traceExplorerLink = router.link('/traces/explorer/waterfall', {
    query: {
      ...query,
      showCriticalPath: false,
      query: `${_apm.ERROR_GROUP_ID}:${groupId}`,
      type: _trace_explorer.TraceSearchType.kql,
      traceId: '',
      transactionId: '',
      waterfallItemId: '',
      detailTab: _transaction_tabs.TransactionTab.timeline
    }
  });
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    hasBorder: true
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "s"
  }, /*#__PURE__*/_react.default.createElement("h3", null, _i18n.i18n.translate('xpack.apm.errorSampleDetails.errorOccurrenceTitle', {
    defaultMessage: 'Error sample'
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: true
  }, !!(errorSampleIds !== null && errorSampleIds !== void 0 && errorSampleIds.length) && /*#__PURE__*/_react.default.createElement(_eui.EuiPagination, {
    pageCount: errorSampleIds.length,
    activePage: sampleActivePage,
    onPageClick: goToSample,
    compressed: true
  })), isTraceExplorerEnabled && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
    "data-test-subj": "apmErrorSampleDetailsLink",
    href: traceExplorerLink
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center",
    gutterSize: "s"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    type: "apmTrace"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    style: {
      whiteSpace: 'nowrap'
    }
  }, _i18n.i18n.translate('xpack.apm.errorSampleDetails.viewOccurrencesInTraceExplorer', {
    defaultMessage: 'Explore traces with this error'
  }))))), (_externalContextMenuI = externalContextMenuItems.value) !== null && _externalContextMenuI !== void 0 && _externalContextMenuI.length ? /*#__PURE__*/_react.default.createElement(_error_ui_actions_context_menu.ErrorUiActionsContextMenu, {
    items: externalContextMenuItems.value
  }) : undefined, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_discover_error_link.DiscoverErrorLink, {
    error: error,
    kuery: kuery
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center",
    gutterSize: "s"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    type: "discoverApp"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    style: {
      whiteSpace: 'nowrap'
    }
  }, _i18n.i18n.translate('xpack.apm.errorSampleDetails.viewOccurrencesInDiscoverButtonLabel', {
    defaultMessage: 'View {occurrencesCount} {occurrencesCount, plural, one {occurrence} other {occurrences}} in Discover',
    values: {
      occurrencesCount
    }
  })))))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), isLoading ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSkeletonText, {
    lines: 2,
    "data-test-sub": "loading-content"
  })) : /*#__PURE__*/_react.default.createElement(_summary.Summary, {
    items: [/*#__PURE__*/_react.default.createElement(_timestamp_tooltip.TimestampTooltip, {
      time: errorData ? error.timestamp.us / 1000 : 0
    }), errorUrl && method ? /*#__PURE__*/_react.default.createElement(_http_info_summary_item.HttpInfoSummaryItem, {
      url: errorUrl,
      method: method,
      status: status
    }) : null, transaction && transaction.user_agent ? /*#__PURE__*/_react.default.createElement(_user_agent_summary_item.UserAgentSummaryItem, transaction.user_agent) : null, transaction && /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
      content: _i18n.i18n.translate('xpack.apm.errorSampleDetails.relatedTransactionSample', {
        defaultMessage: 'Related transaction sample'
      })
    }, /*#__PURE__*/_react.default.createElement(_transaction_detail_link.TransactionDetailLink, {
      traceId: transaction.trace.id,
      transactionId: transaction.transaction.id,
      transactionName: transaction.transaction.name,
      transactionType: transaction.transaction.type,
      serviceName: transaction.service.name,
      offset: offset,
      comparisonEnabled: comparisonEnabled
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      type: "merge"
    }), /*#__PURE__*/_react.default.createElement(TransactionLinkName, null, transaction.transaction.name))), environment ? /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
      content: _i18n.i18n.translate('xpack.apm.errorSampleDetails.serviceEnvironment', {
        defaultMessage: 'Environment'
      })
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
      color: "hollow"
    }, environment)) : null, serviceVersion ? /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
      content: _i18n.i18n.translate('xpack.apm.errorSampleDetails.serviceVersion', {
        defaultMessage: 'Service version'
      })
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
      color: "hollow"
    }, serviceVersion)) : null, isUnhandled ? /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
      color: "warning"
    }, _i18n.i18n.translate('xpack.apm.errorGroupDetails.unhandledLabel', {
      defaultMessage: 'Unhandled'
    })) : null]
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), isLoading ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSkeletonText, {
    lines: 3,
    "data-test-sub": "loading-content"
  })) : /*#__PURE__*/_react.default.createElement(_sample_summary.SampleSummary, {
    error: error
  }), /*#__PURE__*/_react.default.createElement(_error_sample_contextual_insight.ErrorSampleContextualInsight, {
    error: error,
    transaction: transaction
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiTabs, null, tabs.map(({
    key,
    label
  }) => {
    return /*#__PURE__*/_react.default.createElement(_eui.EuiTab, {
      onClick: () => {
        history.replace({
          ...history.location,
          search: (0, _url_helpers.fromQuery)({
            ...(0, _url_helpers.toQuery)(history.location.search),
            detailTab: key
          })
        });
      },
      isSelected: currentTab.key === key,
      key: key
    }, label);
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), isLoading || !error ? /*#__PURE__*/_react.default.createElement(_eui.EuiSkeletonText, {
    lines: 3,
    "data-test-sub": "loading-content"
  }) : /*#__PURE__*/_react.default.createElement(ErrorSampleDetailTabContent, {
    error: error,
    currentTab: currentTab
  }));
}
function ErrorSampleDetailTabContent({
  error,
  currentTab
}) {
  var _error$service$langua, _error$error$log;
  const codeLanguage = error === null || error === void 0 ? void 0 : (_error$service$langua = error.service.language) === null || _error$service$langua === void 0 ? void 0 : _error$service$langua.name;
  const exceptions = (error === null || error === void 0 ? void 0 : error.error.exception) || [];
  const logStackframes = error === null || error === void 0 ? void 0 : (_error$error$log = error.error.log) === null || _error$error$log === void 0 ? void 0 : _error$error$log.stacktrace;
  const isPlaintextException = !!(error !== null && error !== void 0 && error.error.stack_trace) && exceptions.length === 1 && !exceptions[0].stacktrace;
  switch (currentTab.key) {
    case _error_tabs.ErrorTabKey.LogStackTrace:
      return /*#__PURE__*/_react.default.createElement(_stacktrace.Stacktrace, {
        stackframes: logStackframes,
        codeLanguage: codeLanguage
      });
    case _error_tabs.ErrorTabKey.ExceptionStacktrace:
      return isPlaintextException ? /*#__PURE__*/_react.default.createElement(_plaintext_stacktrace.PlaintextStacktrace, {
        message: exceptions[0].message,
        type: exceptions[0].type,
        stacktrace: error === null || error === void 0 ? void 0 : error.error.stack_trace,
        codeLanguage: codeLanguage
      }) : /*#__PURE__*/_react.default.createElement(_exception_stacktrace.ExceptionStacktrace, {
        codeLanguage: codeLanguage,
        exceptions: exceptions
      });
    default:
      return /*#__PURE__*/_react.default.createElement(_error_metadata.ErrorMetadata, {
        error: error
      });
  }
}