"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ComponentTemplateList = void 0;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _analytics = require("@kbn/analytics");
var _i18nReact = require("@kbn/i18n-react");
var _eui = require("@elastic/eui");
var _breadcrumbs = require("../../../services/breadcrumbs");
var _shared_imports = require("../../../../shared_imports");
var _shared_imports2 = require("../shared_imports");
var _constants = require("../constants");
var _component_templates_context = require("../component_templates_context");
var _component_template_details = require("../component_template_details");
var _empty_prompt = require("./empty_prompt");
var _table = require("./table");
var _delete_modal = require("./delete_modal");
var _redirect_path = require("../../../hooks/redirect_path");
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 {
  useGlobalFlyout
} = _shared_imports2.GlobalFlyout;
const ComponentTemplateList = ({
  componentTemplateName,
  history
}) => {
  const {
    addContent: addContentToGlobalFlyout,
    removeContent: removeContentFromGlobalFlyout
  } = useGlobalFlyout();
  const {
    api,
    trackMetric,
    documentation
  } = (0, _component_templates_context.useComponentTemplatesContext)();
  const redirectTo = (0, _redirect_path.useRedirectPath)(history);
  (0, _react.useEffect)(() => {
    _breadcrumbs.breadcrumbService.setBreadcrumbs(_breadcrumbs.IndexManagementBreadcrumb.componentTemplates);
  }, []);
  const {
    data,
    isLoading,
    error,
    resendRequest
  } = api.useLoadComponentTemplates();
  const [componentTemplatesToDelete, setComponentTemplatesToDelete] = (0, _react.useState)([]);
  const goToComponentTemplateList = (0, _react.useCallback)(() => {
    return redirectTo({
      pathname: 'component_templates'
    });
  }, [redirectTo]);
  const goToEditComponentTemplate = (0, _react.useCallback)(name => {
    return history.push({
      pathname: encodeURI(`edit_component_template/${encodeURIComponent(name)}`)
    });
  }, [history]);
  const goToCloneComponentTemplate = (0, _react.useCallback)(name => {
    return history.push({
      pathname: encodeURI(`create_component_template/${encodeURIComponent(name)}`)
    });
  }, [history]);

  // Track component loaded
  (0, _react.useEffect)(() => {
    trackMetric(_analytics.METRIC_TYPE.LOADED, _constants.UIM_COMPONENT_TEMPLATE_LIST_LOAD);
  }, [trackMetric]);
  (0, _react.useEffect)(() => {
    if (componentTemplateName) {
      const actions = [{
        name: _i18n.i18n.translate('xpack.idxMgmt.componentTemplateDetails.editButtonLabel', {
          defaultMessage: 'Edit'
        }),
        icon: 'pencil',
        handleActionClick: () => goToEditComponentTemplate((0, _shared_imports.attemptToURIDecode)(componentTemplateName))
      }, {
        name: _i18n.i18n.translate('xpack.idxMgmt.componentTemplateDetails.cloneActionLabel', {
          defaultMessage: 'Clone'
        }),
        icon: 'copy',
        handleActionClick: () => goToCloneComponentTemplate((0, _shared_imports.attemptToURIDecode)(componentTemplateName))
      }, {
        name: _i18n.i18n.translate('xpack.idxMgmt.componentTemplateDetails.deleteButtonLabel', {
          defaultMessage: 'Delete'
        }),
        icon: 'trash',
        getIsDisabled: details => details._kbnMeta.usedBy.length > 0,
        closePopoverOnClick: true,
        handleActionClick: () => {
          setComponentTemplatesToDelete([(0, _shared_imports.attemptToURIDecode)(componentTemplateName)]);
        }
      }];

      // Open the flyout with the Component Template Details content
      addContentToGlobalFlyout({
        id: 'componentTemplateDetails',
        Component: _component_template_details.ComponentTemplateDetailsFlyoutContent,
        props: {
          onClose: goToComponentTemplateList,
          componentTemplateName,
          showSummaryCallToAction: true,
          actions
        },
        flyoutProps: {
          ..._component_template_details.defaultFlyoutProps,
          onClose: goToComponentTemplateList
        }
      });
    }
  }, [componentTemplateName, goToComponentTemplateList, goToEditComponentTemplate, goToCloneComponentTemplate, addContentToGlobalFlyout, history]);
  (0, _react.useEffect)(() => {
    if (!componentTemplateName) {
      removeContentFromGlobalFlyout('componentTemplateDetails');
    }
  }, [componentTemplateName, removeContentFromGlobalFlyout]);
  if (isLoading) {
    return /*#__PURE__*/_react.default.createElement(_shared_imports.PageLoading, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.home.componentTemplates.list.loadingMessage",
      defaultMessage: "Loading component templates\u2026"
    }));
  }
  let content;
  if (data !== null && data !== void 0 && data.length) {
    content = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      color: "subdued"
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.home.componentTemplates.list.componentTemplatesDescription",
      defaultMessage: "Use component templates to reuse settings, mappings, and aliases configurations in multiple index templates. {learnMoreLink}",
      values: {
        learnMoreLink: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
          href: documentation.componentTemplates,
          target: "_blank",
          external: true
        }, _i18n.i18n.translate('xpack.idxMgmt.componentTemplates.list.learnMoreLinkText', {
          defaultMessage: 'Learn more.'
        }))
      }
    })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), /*#__PURE__*/_react.default.createElement(_table.ComponentTable, {
      componentTemplates: data,
      onReloadClick: resendRequest,
      onDeleteClick: setComponentTemplatesToDelete,
      onEditClick: goToEditComponentTemplate,
      onCloneClick: goToCloneComponentTemplate,
      history: history
    }));
  } else if (data && data.length === 0) {
    content = /*#__PURE__*/_react.default.createElement(_empty_prompt.EmptyPrompt, {
      history: history
    });
  } else if (error) {
    content = /*#__PURE__*/_react.default.createElement(_shared_imports.PageError, {
      title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.idxMgmt.home.componentTemplates.list.loadingErrorMessage",
        defaultMessage: "Error loading component templates"
      }),
      error: error,
      "data-test-subj": "componentTemplatesLoadError"
    });
  }
  return /*#__PURE__*/_react.default.createElement("div", {
    className: _shared_imports.APP_WRAPPER_CLASS,
    "data-test-subj": "componentTemplateList"
  }, content, (componentTemplatesToDelete === null || componentTemplatesToDelete === void 0 ? void 0 : componentTemplatesToDelete.length) > 0 ? /*#__PURE__*/_react.default.createElement(_delete_modal.ComponentTemplatesDeleteModal, {
    callback: deleteResponse => {
      if (deleteResponse !== null && deleteResponse !== void 0 && deleteResponse.hasDeletedComponentTemplates) {
        // refetch the component templates
        resendRequest();
        // go back to list view (if deleted from details flyout)
        goToComponentTemplateList();
      }
      setComponentTemplatesToDelete([]);
    },
    componentTemplatesToDelete: componentTemplatesToDelete
  }) : null);
};
exports.ComponentTemplateList = ComponentTemplateList;