"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SearchableSnapshotField = void 0;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _lodash = require("lodash");
var _i18nReact = require("@kbn/i18n-react");
var _eui = require("@elastic/eui");
var _shared_imports = require("../../../../../../../shared_imports");
var _edit_policy_context = require("../../../../edit_policy_context");
var _form = require("../../../../form");
var _ = require("../../..");
var _searchable_snapshot_data_provider = require("./searchable_snapshot_data_provider");
var _repository_combobox_field = require("./repository_combobox_field");
require("./_searchable_snapshot_field.scss");
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 geti18nTexts = (phase, fullyMountedSearchableSnapshotLink, partiallyMountedSearchableSnapshotLink) => {
  switch (phase) {
    // Hot and cold phases both create fully mounted snapshots.
    case 'hot':
    case 'cold':
      return {
        title: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.fullyMountedSearchableSnapshotField.title', {
          defaultMessage: 'Searchable snapshot'
        }),
        description: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.indexLifecycleMgmt.editPolicy.fullyMountedSearchableSnapshotField.description",
          defaultMessage: "Convert to a fully-mounted index that contains a complete copy of your data and is backed by a snapshot. You can reduce the number of replicas and rely on the snapshot for resiliency. {learnMoreLink}",
          values: {
            learnMoreLink: /*#__PURE__*/_react.default.createElement(_.LearnMoreLink, {
              docPath: fullyMountedSearchableSnapshotLink
            })
          }
        }),
        toggleLabel: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.fullyMountedSearchableSnapshotField.toggleLabel', {
          defaultMessage: 'Convert to fully-mounted index'
        })
      };

    // Frozen phase creates a partially mounted snapshot.
    case 'frozen':
      return {
        title: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.partiallyMountedSearchableSnapshotField.title', {
          defaultMessage: 'Searchable snapshot'
        }),
        description: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.indexLifecycleMgmt.editPolicy.frozenPhase.partiallyMountedSearchableSnapshotField.description",
          defaultMessage: "Convert to a partially-mounted index that caches the index metadata. Data is retrieved from the snapshot as needed to process search requests. This minimizes the index footprint while keeping all of your data fully searchable. {learnMoreLink}",
          values: {
            learnMoreLink: /*#__PURE__*/_react.default.createElement(_.LearnMoreLink, {
              docPath: partiallyMountedSearchableSnapshotLink
            })
          }
        }),
        toggleLabel: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.partiallyMountedSearchableSnapshotField.toggleLabel', {
          defaultMessage: 'Convert to partially-mounted index'
        })
      };
  }
};
const SearchableSnapshotField = ({
  phase,
  canBeDisabled = true
}) => {
  const {
    services: {
      cloud,
      docLinks,
      getUrlForApp
    }
  } = (0, _shared_imports.useKibana)();
  const {
    policy,
    license,
    isNewPolicy
  } = (0, _edit_policy_context.useEditPolicyContext)();
  const {
    isUsingSearchableSnapshotInHotPhase
  } = (0, _form.useConfiguration)();
  const searchableSnapshotRepoPath = `phases.${phase}.actions.searchable_snapshot.snapshot_repository`;
  const [formData] = (0, _shared_imports.useFormData)({
    watch: _form.globalFields.searchableSnapshotRepo.path
  });
  const searchableSnapshotGlobalRepo = (0, _lodash.get)(formData, _form.globalFields.searchableSnapshotRepo.path);
  const isColdPhase = phase === 'cold';
  const isFrozenPhase = phase === 'frozen';
  const isColdOrFrozenPhase = isColdPhase || isFrozenPhase;
  const isDisabledDueToLicense = !license.canUseSearchableSnapshot();
  const [isFieldToggleChecked, setIsFieldToggleChecked] = (0, _react.useState)(() => {
    var _policy$phases$phase, _policy$phases$phase$, _policy$phases$phase$2;
    return Boolean(
    // New policy on cloud should have searchable snapshot on in cold and frozen phase
    isColdOrFrozenPhase && isNewPolicy && (cloud === null || cloud === void 0 ? void 0 : cloud.isCloudEnabled) || ((_policy$phases$phase = policy.phases[phase]) === null || _policy$phases$phase === void 0 ? void 0 : (_policy$phases$phase$ = _policy$phases$phase.actions) === null || _policy$phases$phase$ === void 0 ? void 0 : (_policy$phases$phase$2 = _policy$phases$phase$.searchable_snapshot) === null || _policy$phases$phase$2 === void 0 ? void 0 : _policy$phases$phase$2.snapshot_repository));
  });
  const fullyMountedSearchableSnapshotLink = docLinks.links.elasticsearch.ilmSearchableSnapshot;
  const partiallyMountedSearchableSnapshotLink = docLinks.links.elasticsearch.searchableSnapshotSharedCache;
  const i18nTexts = geti18nTexts(phase, fullyMountedSearchableSnapshotLink, partiallyMountedSearchableSnapshotLink);
  (0, _react.useEffect)(() => {
    if (isDisabledDueToLicense) {
      setIsFieldToggleChecked(false);
    }
  }, [isDisabledDueToLicense]);
  const renderField = () => /*#__PURE__*/_react.default.createElement(_searchable_snapshot_data_provider.SearchableSnapshotDataProvider, null, ({
    error,
    isLoading,
    resendRequest,
    data
  }) => {
    var _data$repositories;
    const repos = (_data$repositories = data === null || data === void 0 ? void 0 : data.repositories) !== null && _data$repositories !== void 0 ? _data$repositories : [];
    let calloutContent;
    if (!isLoading) {
      if (error) {
        calloutContent = /*#__PURE__*/_react.default.createElement(_.FieldLoadingError, {
          resendRequest: resendRequest,
          "data-test-subj": "repositoriesErrorCallout",
          "aria-label": _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.reloadSnapshotRepositoriesLabel', {
            defaultMessage: 'Reload snapshot repositories'
          }),
          title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.indexLifecycleMgmt.editPolicy.loadSnapshotRepositoriesErrorTitle",
            defaultMessage: "Unable to load snapshot repositories"
          }),
          body: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.indexLifecycleMgmt.editPolicy.loadSnapshotRepositoriesErrorBody",
            defaultMessage: "Refresh this field and enter the name of an existing snapshot repository."
          })
        });
      } else if (repos.length === 0) {
        calloutContent = /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
          color: "warning",
          title: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.noSnapshotRepositoriesTitle', {
            defaultMessage: 'No snapshot repositories found'
          })
        }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.indexLifecycleMgmt.editPolicy.noSnapshotRepositoriesFoundBody",
          defaultMessage: "{link} to use searchable snapshots.",
          values: {
            link: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
              href: getUrlForApp('management', {
                path: `data/snapshot_restore/add_repository`
              }),
              target: "_blank"
            }, _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.createSearchableSnapshotLink', {
              defaultMessage: 'Create a snapshot repository'
            }))
          }
        }));
      } else if (searchableSnapshotGlobalRepo && !repos.includes(searchableSnapshotGlobalRepo)) {
        calloutContent = /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
          title: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.noSnapshotRepositoriesWithNameTitle', {
            defaultMessage: 'Repository name not found'
          }),
          color: "warning"
        }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.indexLifecycleMgmt.editPolicy.noSnapshotRepositoryWithNameBody",
          defaultMessage: "Enter the name of an existing repository, or {link} with this name.",
          values: {
            link: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
              href: getUrlForApp('management', {
                path: `data/snapshot_restore/add_repository`
              }),
              target: "_blank"
            }, _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.createSnapshotRepositoryLink', {
              defaultMessage: 'create a new snapshot repository'
            }))
          }
        }));
      }
    }
    return /*#__PURE__*/_react.default.createElement("div", {
      className: "ilmSearchableSnapshotField"
    }, /*#__PURE__*/_react.default.createElement(_form.UseField, {
      path: searchableSnapshotRepoPath,
      defaultValue: !!searchableSnapshotGlobalRepo ? [searchableSnapshotGlobalRepo] : [],
      component: _repository_combobox_field.RepositoryComboBoxField,
      componentProps: {
        globalRepository: searchableSnapshotGlobalRepo,
        isLoading,
        repos,
        noSuggestions: !!(error || repos.length === 0)
      }
    }), calloutContent && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "s"
    }), calloutContent));
  });
  const renderInfoCallout = () => {
    let infoCallout;
    if (phase === 'hot' && isUsingSearchableSnapshotInHotPhase) {
      infoCallout = /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
        size: "s",
        title: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.searchableSnapshotCalloutBody', {
          defaultMessage: 'Force merge, shrink, downsample and read only actions are not allowed when converting data to a fully-mounted index in this phase.'
        }),
        "data-test-subj": "searchableSnapshotFieldsDisabledCallout"
      });
    } else if (isDisabledDueToLicense) {
      infoCallout = /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
        "data-test-subj": "searchableSnapshotDisabledDueToLicense",
        title: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.searchableSnapshotLicenseCalloutTitle', {
          defaultMessage: 'Enterprise license required'
        }),
        iconType: "questionInCircle"
      }, _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.searchableSnapshotLicenseCalloutBody', {
        defaultMessage: 'To create a searchable snapshot an enterprise license is required.'
      }));
    }
    return infoCallout ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), infoCallout, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null)) : undefined;
  };
  return /*#__PURE__*/_react.default.createElement(_.DescribedFormRow, {
    "data-test-subj": `searchableSnapshotField-${phase}`,
    switchProps: canBeDisabled ? {
      checked: isFieldToggleChecked,
      disabled: isDisabledDueToLicense,
      onChange: setIsFieldToggleChecked,
      'data-test-subj': 'searchableSnapshotToggle',
      label: i18nTexts.toggleLabel
    } : undefined,
    title: /*#__PURE__*/_react.default.createElement("h3", null, i18nTexts.title),
    description: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiTextColor, {
      color: "subdued"
    }, i18nTexts.description)),
    fieldNotices: renderInfoCallout(),
    fullWidth: true
  }, isDisabledDueToLicense ? /*#__PURE__*/_react.default.createElement("div", null) : renderField);
};
exports.SearchableSnapshotField = SearchableSnapshotField;