"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSelectFleetServerPolicy = void 0;
var _react = require("react");
var _hooks = require("../../../hooks");
var _services = require("../../../services");
/*
 * 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 useSelectFleetServerPolicy = defaultAgentPolicyId => {
  const [fleetServerPolicyId, setFleetServerPolicyId] = (0, _react.useState)(defaultAgentPolicyId);
  const {
    isLoading,
    isInitialRequest,
    data: agentPoliciesData,
    resendRequest
  } = (0, _hooks.useGetAgentPolicies)({
    full: true
  });
  const eligibleFleetServerPolicies = (0, _react.useMemo)(() => {
    var _agentPoliciesData$it;
    return agentPoliciesData ? (_agentPoliciesData$it = agentPoliciesData.items) === null || _agentPoliciesData$it === void 0 ? void 0 : _agentPoliciesData$it.filter(item => (0, _services.policyHasFleetServer)(item)) : [];
  }, [agentPoliciesData]);
  (0, _react.useEffect)(() => {
    // Default to the first policy found with a fleet server integration installed
    if (eligibleFleetServerPolicies.length === 1 && !fleetServerPolicyId) {
      setFleetServerPolicyId(eligibleFleetServerPolicies[0].id);
    }
  }, [eligibleFleetServerPolicies, fleetServerPolicyId]);
  return {
    isSelectFleetServerPolicyLoading: isLoading && isInitialRequest,
    fleetServerPolicyId,
    setFleetServerPolicyId,
    eligibleFleetServerPolicies,
    refreshEligibleFleetServerPolicies: resendRequest
  };
};
exports.useSelectFleetServerPolicy = useSelectFleetServerPolicy;