"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.NewEnrollmentTokenModal = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _eui = require("@elastic/eui");
var _hooks = require("../hooks");
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.
 */

function validatePolicyId(value) {
  if (value === '') {
    return [_i18n.i18n.translate('xpack.fleet.newEnrollmentKeyForm.policyIdRequireErrorMessage', {
      defaultMessage: 'Policy is required'
    })];
  }
}
function useCreateApiKeyForm(policyIdDefaultValue, onSuccess, onError) {
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const apiKeyNameInput = (0, _hooks.useInput)('');
  const policyIdInput = (0, _hooks.useInput)(policyIdDefaultValue, validatePolicyId);
  const onSubmit = async event => {
    event.preventDefault();
    if (!policyIdInput.validate() || !apiKeyNameInput.validate()) {
      return;
    }
    setIsLoading(true);
    try {
      var _res$data;
      const res = await (0, _hooks.sendCreateEnrollmentAPIKey)({
        name: apiKeyNameInput.value,
        policy_id: policyIdInput.value
      });
      if (res.error) {
        throw res.error;
      }
      policyIdInput.clear();
      apiKeyNameInput.clear();
      setIsLoading(false);
      if ((_res$data = res.data) !== null && _res$data !== void 0 && _res$data.item) {
        onSuccess(res.data.item);
      }
    } catch (error) {
      setIsLoading(false);
      onError(error);
    }
  };
  return {
    isLoading,
    onSubmit,
    policyIdInput,
    apiKeyNameInput
  };
}
const NewEnrollmentTokenModal = ({
  onClose,
  agentPolicies = []
}) => {
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const selectPolicyOptions = (0, _react.useMemo)(() => {
    return agentPolicies.filter(agentPolicy => !agentPolicy.is_managed).map(agentPolicy => ({
      value: agentPolicy.id,
      text: agentPolicy.name
    }));
  }, [agentPolicies]);
  const form = useCreateApiKeyForm(selectPolicyOptions.length > 0 ? selectPolicyOptions[0].value : undefined, key => {
    onClose(key);
    notifications.toasts.addSuccess(_i18n.i18n.translate('xpack.fleet.newEnrollmentKey.keyCreatedToasts', {
      defaultMessage: 'Enrollment token created'
    }));
  }, error => {
    notifications.toasts.addError(error, {
      title: 'Error'
    });
  });
  const body = /*#__PURE__*/_react.default.createElement(_eui.EuiForm, null, /*#__PURE__*/_react.default.createElement("form", {
    onSubmit: form.onSubmit
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    label: _i18n.i18n.translate('xpack.fleet.newEnrollmentKey.nameLabel', {
      defaultMessage: 'Token name'
    }),
    helpText: _i18n.i18n.translate('xpack.fleet.newEnrollmentKey.helpText', {
      defaultMessage: 'Token id will be used when this is left empty.'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, (0, _extends2.default)({
    "data-test-subj": "createEnrollmentTokenNameField",
    name: "name",
    autoComplete: "off",
    placeholder: _i18n.i18n.translate('xpack.fleet.newEnrollmentKey.placeholder', {
      defaultMessage: 'Enter a token name'
    })
  }, form.apiKeyNameInput.props))), /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, (0, _extends2.default)({
    label: _i18n.i18n.translate('xpack.fleet.newEnrollmentKey.policyLabel', {
      defaultMessage: 'Policy'
    })
  }, form.policyIdInput.formRowProps), /*#__PURE__*/_react.default.createElement(_eui.EuiSelect, (0, _extends2.default)({
    "data-test-subj": "createEnrollmentTokenSelectField",
    required: true
  }, form.policyIdInput.props, {
    options: selectPolicyOptions
  })))));
  return /*#__PURE__*/_react.default.createElement(_eui.EuiConfirmModal, {
    isLoading: form.isLoading,
    title: _i18n.i18n.translate('xpack.fleet.newEnrollmentKey.modalTitle', {
      defaultMessage: 'Create enrollment token'
    }),
    onCancel: () => onClose(),
    cancelButtonText: _i18n.i18n.translate('xpack.fleet.newEnrollmentKey.cancelButtonLabel', {
      defaultMessage: 'Cancel'
    }),
    onConfirm: form.onSubmit,
    confirmButtonText: _i18n.i18n.translate('xpack.fleet.newEnrollmentKey.submitButton', {
      defaultMessage: 'Create enrollment token'
    }),
    confirmButtonDisabled: !form.policyIdInput.value
  }, body);
};
exports.NewEnrollmentTokenModal = NewEnrollmentTokenModal;