"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Popover = Popover;
var _eui = require("@elastic/eui");
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _apm = require("../../../../../common/es_fields/apm");
var _use_theme = require("../../../../hooks/use_theme");
var _use_trace_explorer_enabled_setting = require("../../../../hooks/use_trace_explorer_enabled_setting");
var _cytoscape = require("../cytoscape");
var _cytoscape_options = require("../cytoscape_options");
var _dependency_contents = require("./dependency_contents");
var _edge_contents = require("./edge_contents");
var _externals_list_contents = require("./externals_list_contents");
var _resource_contents = require("./resource_contents");
var _service_contents = require("./service_contents");
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 getContentsComponent(selectedElementData, isTraceExplorerEnabled) {
  if (selectedElementData.groupedConnections && Array.isArray(selectedElementData.groupedConnections)) {
    return _externals_list_contents.ExternalsListContents;
  }
  if (selectedElementData[_apm.SERVICE_NAME]) {
    return _service_contents.ServiceContents;
  }
  if (selectedElementData[_apm.SPAN_TYPE] === 'resource') {
    return _resource_contents.ResourceContents;
  }
  if (isTraceExplorerEnabled && selectedElementData.source && selectedElementData.target) {
    return _edge_contents.EdgeContents;
  }
  return _dependency_contents.DependencyContents;
}
function Popover({
  focusedServiceName,
  environment,
  kuery,
  start,
  end
}) {
  var _selectedElement$rend, _selectedElement$rend2, _cy$zoom, _selectedElement$heig, _selectedElement$data, _selectedElementData$;
  const theme = (0, _use_theme.useTheme)();
  const cy = (0, _react.useContext)(_cytoscape.CytoscapeContext);
  const [selectedElement, setSelectedElement] = (0, _react.useState)(undefined);
  const deselect = (0, _react.useCallback)(() => {
    if (cy) {
      cy.elements().unselect();
    }
    setSelectedElement(undefined);
  }, [cy, setSelectedElement]);
  const isTraceExplorerEnabled = (0, _use_trace_explorer_enabled_setting.useTraceExplorerEnabledSetting)();
  const renderedHeight = (_selectedElement$rend = selectedElement === null || selectedElement === void 0 ? void 0 : selectedElement.renderedHeight()) !== null && _selectedElement$rend !== void 0 ? _selectedElement$rend : 0;
  const renderedWidth = (_selectedElement$rend2 = selectedElement === null || selectedElement === void 0 ? void 0 : selectedElement.renderedWidth()) !== null && _selectedElement$rend2 !== void 0 ? _selectedElement$rend2 : 0;
  const box = selectedElement === null || selectedElement === void 0 ? void 0 : selectedElement.renderedBoundingBox({});
  const x = box ? box.x1 + box.w / 2 : -10000;
  const y = box ? box.y1 + box.h / 2 : -10000;
  const isOpen = !!selectedElement;
  const triggerStyle = {
    background: 'transparent',
    height: renderedHeight,
    position: 'absolute',
    width: renderedWidth
  };
  const trigger = /*#__PURE__*/_react.default.createElement("div", {
    style: triggerStyle
  });
  const zoom = (_cy$zoom = cy === null || cy === void 0 ? void 0 : cy.zoom()) !== null && _cy$zoom !== void 0 ? _cy$zoom : 1;
  const height = (_selectedElement$heig = selectedElement === null || selectedElement === void 0 ? void 0 : selectedElement.height()) !== null && _selectedElement$heig !== void 0 ? _selectedElement$heig : 0;
  const translateY = y - (zoom + 1) * height / 4;
  const popoverStyle = {
    position: 'absolute',
    transform: `translate(${x}px, ${translateY}px)`
  };
  const selectedElementData = (_selectedElement$data = selectedElement === null || selectedElement === void 0 ? void 0 : selectedElement.data()) !== null && _selectedElement$data !== void 0 ? _selectedElement$data : {};
  const popoverRef = (0, _react.useRef)(null);
  const selectedElementId = selectedElementData.id;

  // Set up Cytoscape event handlers
  (0, _react.useEffect)(() => {
    const selectHandler = event => {
      setSelectedElement(event.target);
    };
    if (cy) {
      cy.on('select', 'node', selectHandler);
      cy.on('unselect', 'node', deselect);
      cy.on('viewport', deselect);
      cy.on('drag', 'node', deselect);
      if (isTraceExplorerEnabled) {
        cy.on('select', 'edge', selectHandler);
        cy.on('unselect', 'edge', deselect);
      }
    }
    return () => {
      if (cy) {
        cy.removeListener('select', 'node', selectHandler);
        cy.removeListener('unselect', 'node', deselect);
        cy.removeListener('viewport', undefined, deselect);
        cy.removeListener('drag', 'node', deselect);
        cy.removeListener('select', 'edge', selectHandler);
        cy.removeListener('unselect', 'edge', deselect);
      }
    };
  }, [cy, deselect, isTraceExplorerEnabled]);

  // Handle positioning of popover. This makes it so the popover positions
  // itself correctly and the arrows are always pointing to where they should.
  (0, _react.useEffect)(() => {
    if (popoverRef.current) {
      popoverRef.current.positionPopoverFluid();
    }
  }, [popoverRef, x, y]);
  const centerSelectedNode = (0, _react.useCallback)(event => {
    event.preventDefault();
    if (cy) {
      cy.animate({
        ...(0, _cytoscape_options.getAnimationOptions)(theme),
        center: {
          eles: cy.getElementById(selectedElementId)
        }
      });
    }
  }, [cy, selectedElementId, theme]);
  const isAlreadyFocused = focusedServiceName === selectedElementId;
  const onFocusClick = isAlreadyFocused ? centerSelectedNode : _event => deselect();
  const ContentsComponent = getContentsComponent(selectedElementData, isTraceExplorerEnabled);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPopover, {
    anchorPosition: 'upCenter',
    button: trigger,
    closePopover: () => {},
    isOpen: isOpen,
    ref: popoverRef,
    style: popoverStyle
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    direction: "column",
    gutterSize: "s",
    style: {
      minWidth: _cytoscape_options.popoverWidth
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "xxs"
  }, /*#__PURE__*/_react.default.createElement("h3", {
    style: {
      wordBreak: 'break-all'
    }
  }, (_selectedElementData$ = selectedElementData.label) !== null && _selectedElementData$ !== void 0 ? _selectedElementData$ : selectedElementId, kuery && /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
    position: "bottom",
    content: _i18n.i18n.translate('xpack.apm.serviceMap.kqlFilterInfo', {
      defaultMessage: 'The KQL filter is not applied in the displayed stats.'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    tabIndex: 0,
    type: "iInCircle"
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiHorizontalRule, {
    margin: "xs"
  })), /*#__PURE__*/_react.default.createElement(ContentsComponent, {
    onFocusClick: onFocusClick,
    elementData: selectedElementData,
    environment: environment,
    kuery: kuery,
    start: start,
    end: end
  })));
}