"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useServiceToken = void 0;
var _react = require("react");
var _i18n = require("@kbn/i18n");
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 useServiceToken = () => {
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const [serviceToken, setServiceToken] = (0, _react.useState)();
  const [isLoadingServiceToken, setIsLoadingServiceToken] = (0, _react.useState)(false);
  const generateServiceToken = (0, _react.useCallback)(async () => {
    setIsLoadingServiceToken(true);
    try {
      const {
        data
      } = await (0, _hooks.sendGenerateServiceToken)();
      if (data !== null && data !== void 0 && data.value) {
        setServiceToken(data === null || data === void 0 ? void 0 : data.value);
      }
    } catch (err) {
      notifications.toasts.addError(err, {
        title: _i18n.i18n.translate('xpack.fleet.fleetServerSetup.errorGeneratingTokenTitleText', {
          defaultMessage: 'Error generating token'
        })
      });
    } finally {
      setIsLoadingServiceToken(false);
    }
  }, [notifications.toasts]);
  return {
    serviceToken,
    isLoadingServiceToken,
    generateServiceToken
  };
};
exports.useServiceToken = useServiceToken;