"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFleetServerUnhealthy = useFleetServerUnhealthy;
var _i18n = require("@kbn/i18n");
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.
 */

function useFleetServerUnhealthy() {
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const [isLoading, setIsLoading] = (0, _react.useState)(true);
  const [isUnhealthy, setIsUnhealthy] = (0, _react.useState)(false);
  const fetchData = (0, _react.useCallback)(async () => {
    try {
      var _packagePoliciesRes$d, _packagePoliciesRes$d2;
      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}`
      });
      if (packagePoliciesRes.error) {
        throw packagePoliciesRes.error;
      }
      const agentPolicyIds = [...new Set((_packagePoliciesRes$d = (_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) {
        var _agentStatusesRes$dat, _agentStatusesRes$dat2;
        const agentStatusesRes = await (0, _hooks.sendGetAgentStatus)({
          kuery: agentPolicyIds.map(policyId => `policy_id:${policyId}`).join(' or ')
        });
        if (agentStatusesRes.error) {
          throw agentStatusesRes.error;
        }
        if (((_agentStatusesRes$dat = agentStatusesRes.data) === null || _agentStatusesRes$dat === void 0 ? void 0 : _agentStatusesRes$dat.results.online) === 0 && ((_agentStatusesRes$dat2 = agentStatusesRes.data) === null || _agentStatusesRes$dat2 === void 0 ? void 0 : _agentStatusesRes$dat2.results.updating) === 0) {
          setIsUnhealthy(true);
        }
      }
      setIsLoading(false);
    } catch (err) {
      notifications.toasts.addError(err, {
        title: _i18n.i18n.translate('xpack.fleet.fleetServerUnhealthy.requestError', {
          defaultMessage: 'An error happened while fetching fleet server status'
        })
      });
      setIsLoading(false);
    }
  }, [notifications.toasts]);
  (0, _react.useEffect)(() => {
    fetchData();
  }, [fetchData]);
  return {
    isLoading,
    isUnhealthy
  };
}