"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useLatestFleetServers = void 0;
var _react = require("react");
var _constants = require("../../../constants");
var _hooks = require("../../../hooks");
/*
 * 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 = 10 * 1000; // 10 secs

const useLatestFleetServers = opts => {
  const [agentIds, setAgentIds] = (0, _react.useState)([]);
  const timeout = (0, _react.useRef)(undefined);
  const getNewAgentIds = (0, _react.useCallback)(async () => {
    var _packagePoliciesRes$d, _packagePoliciesRes$d2, _request$data$items$m, _request$data;
    const packagePoliciesRes = await (0, _hooks.sendGetPackagePolicies)({
      page: 1,
      perPage: _constants.SO_SEARCH_LIMIT,
      kuery: `${_constants.PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${_constants.FLEET_SERVER_PACKAGE}`
    });
    const agentPolicyIds = [...new Set((_packagePoliciesRes$d = packagePoliciesRes === null || packagePoliciesRes === void 0 ? void 0 : (_packagePoliciesRes$d2 = packagePoliciesRes.data) === null || _packagePoliciesRes$d2 === void 0 ? void 0 : _packagePoliciesRes$d2.items.map(p => p.policy_id)) !== null && _packagePoliciesRes$d !== void 0 ? _packagePoliciesRes$d : [])];
    if (agentPolicyIds.length === 0) {
      return;
    }
    const kuery = `(${agentPolicyIds.map(policyId => `${_constants.AGENTS_PREFIX}.policy_id:"${policyId}"`).join(' or ')}) and not (_exists_:"${_constants.AGENTS_PREFIX}.unenrolled_at") and ${_constants.AGENTS_PREFIX}.enrolled_at >= now-10m`;
    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]);
  (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, getNewAgentIds]);
  return {
    hasRecentlyEnrolledFleetServers: agentIds.length > 0
  };
};
exports.useLatestFleetServers = useLatestFleetServers;