"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EnrollmentTokenListPage = void 0;
var _i18n = require("@kbn/i18n");
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _api_key_field = require("../../../../../components/api_key_field");
var _constants = require("../../../constants");
var _components = require("../../../components");
var _hooks = require("../../../hooks");
var _search_bar = require("../../../components/search_bar");
var _layouts = require("../../../layouts");
var _confirm_delete_modal = require("./components/confirm_delete_modal");
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.
 */

const DeleteButton = ({
  apiKey,
  refresh
}) => {
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const [state, setState] = (0, _react.useState)('CONFIRM_HIDDEN');
  const onCancel = () => setState('CONFIRM_HIDDEN');
  const onConfirm = async () => {
    try {
      const res = await (0, _hooks.sendDeleteOneEnrollmentAPIKey)(apiKey.id);
      if (res.error) {
        throw res.error;
      }
    } catch (err) {
      notifications.toasts.addError(err, {
        title: 'Error'
      });
    }
    setState('CONFIRM_HIDDEN');
    refresh();
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, state === 'CONFIRM_VISIBLE' && /*#__PURE__*/_react.default.createElement(_confirm_delete_modal.ConfirmEnrollmentTokenDelete, {
    enrollmentKey: apiKey,
    onCancel: onCancel,
    onConfirm: onConfirm
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
    content: _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.revokeTokenButtonLabel', {
      defaultMessage: 'Revoke token'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
    "data-test-subj": "enrollmentTokenTable.revokeBtn",
    "aria-label": _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.revokeTokenButtonLabel', {
      defaultMessage: 'Revoke token'
    }),
    onClick: () => setState('CONFIRM_VISIBLE'),
    iconType: "trash",
    color: "danger"
  })));
};
const EnrollmentTokenListPage = () => {
  var _enrollmentAPIKeysReq, _enrollmentAPIKeysReq2, _enrollmentAPIKeysReq3;
  (0, _hooks.useBreadcrumbs)('enrollment_tokens');
  const [isModalOpen, setModalOpen] = (0, _react.useState)(false);
  const [search, setSearch] = (0, _react.useState)('');
  const {
    pagination,
    setPagination,
    pageSizeOptions
  } = (0, _hooks.usePagination)();
  const enrollmentAPIKeysRequest = (0, _hooks.useGetEnrollmentAPIKeys)({
    page: pagination.currentPage,
    perPage: pagination.pageSize,
    kuery: search.trim() !== '' ? search : undefined
  });
  const agentPoliciesRequest = (0, _hooks.useGetAgentPolicies)({
    page: 1,
    perPage: _constants.SO_SEARCH_LIMIT
  });
  const agentPolicies = agentPoliciesRequest.data ? agentPoliciesRequest.data.items : [];
  const agentPoliciesById = agentPolicies.reduce((acc, policy) => {
    acc[policy.id] = policy;
    return acc;
  }, {});
  const total = (_enrollmentAPIKeysReq = enrollmentAPIKeysRequest === null || enrollmentAPIKeysRequest === void 0 ? void 0 : (_enrollmentAPIKeysReq2 = enrollmentAPIKeysRequest.data) === null || _enrollmentAPIKeysReq2 === void 0 ? void 0 : _enrollmentAPIKeysReq2.total) !== null && _enrollmentAPIKeysReq !== void 0 ? _enrollmentAPIKeysReq : 0;
  const rowItems = (enrollmentAPIKeysRequest === null || enrollmentAPIKeysRequest === void 0 ? void 0 : (_enrollmentAPIKeysReq3 = enrollmentAPIKeysRequest.data) === null || _enrollmentAPIKeysReq3 === void 0 ? void 0 : _enrollmentAPIKeysReq3.items.filter(enrollmentKey => {
    if (!agentPolicies.length || !enrollmentKey.policy_id) return false;
    const agentPolicy = agentPoliciesById[enrollmentKey.policy_id];
    return !(agentPolicy !== null && agentPolicy !== void 0 && agentPolicy.is_managed);
  })) || [];
  const columns = [{
    field: 'name',
    name: _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.nameTitle', {
      defaultMessage: 'Name'
    }),
    render: value => /*#__PURE__*/_react.default.createElement("span", {
      className: "eui-textTruncate",
      title: value
    }, value)
  }, {
    field: 'id',
    name: _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.secretTitle', {
      defaultMessage: 'Secret'
    }),
    width: '215px',
    render: apiKeyId => {
      return /*#__PURE__*/_react.default.createElement(_api_key_field.ApiKeyField, {
        apiKeyId: apiKeyId,
        sendGetAPIKey: _hooks.sendGetOneEnrollmentAPIKey,
        tokenGetter: response => {
          var _response$data;
          return (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.item.api_key;
        },
        length: 60
      });
    }
  }, {
    field: 'policy_id',
    name: _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.policyTitle', {
      defaultMessage: 'Agent policy'
    }),
    render: policyId => {
      const agentPolicy = agentPoliciesById[policyId];
      const value = agentPolicy ? agentPolicy.name : policyId;
      return /*#__PURE__*/_react.default.createElement("span", {
        className: "eui-textTruncate",
        title: value
      }, value);
    }
  }, {
    field: 'created_at',
    name: _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.createdAtTitle', {
      defaultMessage: 'Created on'
    }),
    width: '150px',
    render: createdAt => {
      return createdAt ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedDate, {
        year: "numeric",
        month: "short",
        day: "2-digit",
        value: createdAt
      }) : null;
    }
  }, {
    field: 'active',
    name: _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.activeTitle', {
      defaultMessage: 'Active'
    }),
    width: '70px',
    align: 'center',
    render: active => {
      return /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        size: "m",
        color: active ? 'success' : 'danger',
        type: "dot"
      });
    }
  }, {
    field: 'actions',
    name: _i18n.i18n.translate('xpack.fleet.enrollmentTokensList.actionsTitle', {
      defaultMessage: 'Actions'
    }),
    width: '70px',
    render: (_, apiKey) => {
      const agentPolicy = agentPolicies.find(c => c.id === apiKey.policy_id);
      const canUnenroll = apiKey.active && !(agentPolicy !== null && agentPolicy !== void 0 && agentPolicy.is_managed);
      return canUnenroll && /*#__PURE__*/_react.default.createElement(DeleteButton, {
        apiKey: apiKey,
        refresh: () => enrollmentAPIKeysRequest.resendRequest()
      });
    }
  }];
  const isLoading = enrollmentAPIKeysRequest.isLoading && enrollmentAPIKeysRequest.isInitialRequest || agentPoliciesRequest.isLoading && agentPoliciesRequest.isInitialRequest;
  return /*#__PURE__*/_react.default.createElement(_layouts.DefaultLayout, {
    section: "enrollment_tokens"
  }, isModalOpen && /*#__PURE__*/_react.default.createElement(_components.NewEnrollmentTokenModal, {
    agentPolicies: agentPolicies,
    onClose: key => {
      setModalOpen(false);
      enrollmentAPIKeysRequest.resendRequest();
    }
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    color: "subdued"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.enrollmentTokensList.pageDescription",
    defaultMessage: "Create and revoke enrollment tokens. An enrollment token enables one or more agents to enroll in Fleet and send data."
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_search_bar.SearchBar, {
    value: search,
    onChange: newSearch => {
      setPagination({
        ...pagination,
        currentPage: 1
      });
      setSearch(newSearch);
    },
    indexPattern: _constants.ENROLLMENT_API_KEYS_INDEX,
    fieldPrefix: _constants.FLEET_ENROLLMENT_API_PREFIX,
    dataTestSubj: "enrollmentKeysList.queryInput"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    "data-test-subj": "createEnrollmentTokenButton",
    fill: true,
    iconType: "plusInCircle",
    onClick: () => setModalOpen(true)
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.enrollmentTokensList.newKeyButton",
    defaultMessage: "Create enrollment token"
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiBasicTable, {
    "data-test-subj": "enrollmentTokenListTable",
    loading: isLoading,
    hasActions: true,
    noItemsMessage: isLoading ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.fleet.enrollemntAPIKeyList.loadingTokensMessage",
      defaultMessage: "Loading enrollment tokens..."
    }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.fleet.enrollemntAPIKeyList.emptyMessage",
      defaultMessage: "No enrollment tokens found."
    }),
    items: total ? rowItems : [],
    itemId: "id",
    columns: columns,
    pagination: {
      pageIndex: pagination.currentPage - 1,
      pageSize: pagination.pageSize,
      totalItemCount: total,
      pageSizeOptions
    },
    onChange: ({
      page
    }) => {
      const newPagination = {
        ...pagination,
        currentPage: page.index + 1,
        pageSize: page.size
      };
      setPagination(newPagination);
    }
  }));
};
exports.EnrollmentTokenListPage = EnrollmentTokenListPage;