"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getConnections = getConnections;
exports.getServiceMapFromTraceIds = getServiceMapFromTraceIds;
var _fetch_service_paths_from_trace_ids = require("./fetch_service_paths_from_trace_ids");
var _transform_service_map_responses = require("./transform_service_map_responses");
/*
 * 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 getConnections({
  paths
}) {
  if (!paths) {
    return [];
  }
  const connectionsById = new Map();
  paths.forEach(path => {
    path.forEach((location, i) => {
      const prev = path[i - 1];
      if (prev) {
        const connection = {
          source: prev,
          destination: location
        };
        const id = (0, _transform_service_map_responses.getConnectionId)(connection);
        if (!connectionsById.has(id)) {
          connectionsById.set(id, connection);
        }
      }
    });
  });
  return Array.from(connectionsById.values());
}
async function getServiceMapFromTraceIds({
  apmEventClient,
  traceIds,
  start,
  end,
  terminateAfter,
  logger
}) {
  var _serviceMapFromTraceI, _serviceMapScriptedAg;
  const serviceMapFromTraceIdsScriptResponse = await (0, _fetch_service_paths_from_trace_ids.fetchServicePathsFromTraceIds)({
    apmEventClient,
    traceIds,
    start,
    end,
    terminateAfter
  });
  logger.debug('Received scripted metric agg response');
  const serviceMapScriptedAggValue = (_serviceMapFromTraceI = serviceMapFromTraceIdsScriptResponse.aggregations) === null || _serviceMapFromTraceI === void 0 ? void 0 : _serviceMapFromTraceI.service_map.value;
  return {
    connections: getConnections({
      paths: serviceMapScriptedAggValue === null || serviceMapScriptedAggValue === void 0 ? void 0 : serviceMapScriptedAggValue.paths
    }),
    discoveredServices: (_serviceMapScriptedAg = serviceMapScriptedAggValue === null || serviceMapScriptedAggValue === void 0 ? void 0 : serviceMapScriptedAggValue.discoveredServices) !== null && _serviceMapScriptedAg !== void 0 ? _serviceMapScriptedAg : []
  };
}