"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.usePollingAgentCount = exports.ConfirmAgentEnrollment = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _i18n = require("@kbn/i18n");
var _hooks = require("../../hooks");
var _constants = require("../../constants");
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 POLLING_INTERVAL_MS = 5 * 1000; // 5 sec

/**
 * Hook for finding agents enrolled since component was rendered. Should be
 * used by parent component to power rendering
 * @param policyId
 * @returns agentIds
 */
const usePollingAgentCount = (policyId, opts) => {
  const [agentIds, setAgentIds] = (0, _react.useState)([]);
  const [didPollInitially, setDidPollInitially] = (0, _react.useState)(false);
  const timeout = (0, _react.useRef)(undefined);
  const lowerTimeLimitKuery = opts !== null && opts !== void 0 && opts.noLowerTimeLimit ? '' : `and ${_constants.AGENTS_PREFIX}.enrolled_at >= now-10m`;
  const kuery = `${_constants.AGENTS_PREFIX}.policy_id:"${policyId}" and not (_exists_:"${_constants.AGENTS_PREFIX}.unenrolled_at") ${lowerTimeLimitKuery}`;
  const getNewAgentIds = (0, _react.useCallback)(async () => {
    var _request$data$items$m, _request$data;
    const request = await (0, _hooks.sendGetAgents)({
      kuery,
      showInactive: false
    });
    const newAgentIds = (_request$data$items$m = (_request$data = request.data) === null || _request$data === void 0 ? void 0 : _request$data.items.map(i => i.id)) !== null && _request$data$items$m !== void 0 ? _request$data$items$m : agentIds;
    if (newAgentIds.some(id => !agentIds.includes(id))) {
      setAgentIds(newAgentIds);
    }
  }, [agentIds, kuery]);

  // optionally poll once on first render
  if (!didPollInitially && opts !== null && opts !== void 0 && opts.pollImmediately) {
    getNewAgentIds();
    setDidPollInitially(true);
  }
  (0, _react.useEffect)(() => {
    let isAborted = false;
    const poll = () => {
      timeout.current = window.setTimeout(async () => {
        getNewAgentIds();
        if (!isAborted) {
          poll();
        }
      }, POLLING_INTERVAL_MS);
    };
    poll();
    if (isAborted || agentIds.length > 0) clearTimeout(timeout.current);
    return () => {
      isAborted = true;
    };
  }, [agentIds, policyId, kuery, getNewAgentIds]);
  return agentIds;
};
exports.usePollingAgentCount = usePollingAgentCount;
const ConfirmAgentEnrollment = ({
  policyId,
  troubleshootLink,
  onClickViewAgents,
  agentCount,
  showLoading = false
}) => {
  const {
    getHref
  } = (0, _hooks.useLink)();
  const {
    application
  } = (0, _hooks.useStartServices)();
  const showViewAgents = !!onClickViewAgents;
  const TroubleshootLink = () => /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
    target: "_blank",
    external: true,
    href: troubleshootLink
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.enrollmentInstructions.troubleshootingLink",
    defaultMessage: "troubleshooting guide"
  }));
  const onButtonClick = () => {
    if (onClickViewAgents) onClickViewAgents();
    const href = getHref('agent_list');
    application.navigateToUrl(href);
  };
  if (!policyId || agentCount === 0 && !showLoading) {
    return /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      "data-test-subj": "ConfirmAgentEnrollmentCallOut.troubleshooting",
      id: "xpack.fleet.enrollmentInstructions.troubleshootingText",
      defaultMessage: "If you are having trouble connecting, see our {link}.",
      values: {
        link: /*#__PURE__*/_react.default.createElement(TroubleshootLink, null)
      }
    }));
  }
  if (showLoading && !agentCount) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
      size: "m",
      color: "primary",
      iconType: _eui.EuiLoadingSpinner,
      title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.fleet.agentEnrollment.loading.listening",
        defaultMessage: "Listening for agent..."
      })
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.fleet.agentEnrollment.loading.instructions",
      defaultMessage: "After the agent starts up, the Elastic Stack listens for the agent and confirms the enrollment in Fleet. If you're having trouble connecting, check out the {link}.",
      values: {
        link: /*#__PURE__*/_react.default.createElement(TroubleshootLink, null)
      }
    })));
  }
  return /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
    "data-test-subj": "ConfirmAgentEnrollmentCallOut",
    title: _i18n.i18n.translate('xpack.fleet.agentEnrollment.confirmation.title', {
      defaultMessage: '{agentCount} {agentCount, plural, one {agent has} other {agents have}} been enrolled.',
      values: {
        agentCount
      }
    }),
    color: "success",
    iconType: "check"
  }, showViewAgents && /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    onClick: onButtonClick,
    color: "success",
    "data-test-subj": "ConfirmAgentEnrollmentButton"
  }, _i18n.i18n.translate('xpack.fleet.agentEnrollment.confirmation.button', {
    defaultMessage: 'View enrolled agents'
  })));
};
exports.ConfirmAgentEnrollment = ConfirmAgentEnrollment;