"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ComponentTemplatesSelector = void 0;
var _classnames = _interopRequireDefault(require("classnames"));
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _i18n = require("@kbn/i18n");
var _shared_imports = require("../shared_imports");
var _component_template_details = require("../component_template_details");
var _components = require("./components");
var _component_templates = require("./component_templates");
var _component_templates_selection = require("./component_templates_selection");
var _component_templates_context = require("../component_templates_context");
require("./component_templates_selector.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 {
  useGlobalFlyout
} = _shared_imports.GlobalFlyout;
const i18nTexts = {
  icons: {
    view: _i18n.i18n.translate('xpack.idxMgmt.componentTemplatesSelector.viewItemIconLabel', {
      defaultMessage: 'View'
    }),
    select: _i18n.i18n.translate('xpack.idxMgmt.componentTemplatesSelector.selectItemIconLabel', {
      defaultMessage: 'Select'
    }),
    remove: _i18n.i18n.translate('xpack.idxMgmt.componentTemplatesSelector.removeItemIconLabel', {
      defaultMessage: 'Remove'
    })
  }
};
const ComponentTemplatesSelector = ({
  onChange,
  defaultValue,
  onComponentsLoaded,
  docUri,
  emptyPrompt: {
    text,
    showCreateButton
  } = {}
}) => {
  const {
    data: components,
    isLoading,
    error
  } = (0, _component_templates_context.useApi)().useLoadComponentTemplates();
  const {
    addContent: addContentToGlobalFlyout,
    removeContent: removeContentFromGlobalFlyout
  } = useGlobalFlyout();
  const [selectedComponent, setSelectedComponent] = (0, _react.useState)(null);
  const [componentsSelected, setComponentsSelected] = (0, _react.useState)([]);
  const isInitialized = (0, _react.useRef)(false);
  const hasSelection = Object.keys(componentsSelected).length > 0;
  const hasComponents = components && components.length > 0 ? true : false;
  const closeComponentTemplateDetails = () => {
    setSelectedComponent(null);
  };
  (0, _react.useEffect)(() => {
    if (components) {
      if (defaultValue && defaultValue.length > 0 && componentsSelected.length === 0 && isInitialized.current === false) {
        // Once the components are fetched, we check the ones previously selected
        // from the prop "defaultValue" passed.
        const nextComponentsSelected = defaultValue.map(name => components.find(comp => comp.name === name)).filter(Boolean);
        setComponentsSelected(nextComponentsSelected);
        onChange(nextComponentsSelected.map(({
          name
        }) => name));
        isInitialized.current = true;
      } else {
        onChange(componentsSelected.map(({
          name
        }) => name));
      }
    }
  }, [defaultValue, components, componentsSelected, onChange]);
  (0, _react.useEffect)(() => {
    if (!isLoading && !error) {
      onComponentsLoaded(components !== null && components !== void 0 ? components : []);
    }
  }, [isLoading, error, components, onComponentsLoaded]);
  (0, _react.useEffect)(() => {
    if (selectedComponent) {
      // Open the flyout with the Component Template Details content
      addContentToGlobalFlyout({
        id: 'componentTemplateDetails',
        Component: _component_template_details.ComponentTemplateDetailsFlyoutContent,
        props: {
          onClose: closeComponentTemplateDetails,
          componentTemplateName: selectedComponent
        },
        flyoutProps: {
          ..._component_template_details.defaultFlyoutProps,
          onClose: closeComponentTemplateDetails
        },
        cleanUpFunc: () => {
          setSelectedComponent(null);
        }
      });
    }
  }, [selectedComponent, addContentToGlobalFlyout]);
  (0, _react.useEffect)(() => {
    if (!selectedComponent) {
      removeContentFromGlobalFlyout('componentTemplateDetails');
    }
  }, [selectedComponent, removeContentFromGlobalFlyout]);
  const onSelectionReorder = reorderedComponents => {
    setComponentsSelected(reorderedComponents);
  };
  const renderLoading = () => /*#__PURE__*/_react.default.createElement(_shared_imports.SectionLoading, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.componentTemplatesSelector.loadingComponentsDescription",
    defaultMessage: "Loading component templates\u2026"
  }));
  const renderError = () => /*#__PURE__*/_react.default.createElement(_shared_imports.SectionError, {
    title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.componentTemplatesSelector.loadingComponentsErrorMessage",
      defaultMessage: "Error loading components"
    }),
    error: error
  });
  const renderSelector = () => /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    className: "componentTemplatesSelector"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    className: (0, _classnames.default)('componentTemplatesSelector__selection', {
      'componentTemplatesSelector__selection--is-empty': !hasSelection
    }),
    "data-test-subj": "componentTemplatesSelection"
  }, hasSelection ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
    className: "componentTemplatesSelector__selection__header"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.componentTemplatesSelector.selectionHeader.componentsSelectedLabel",
    defaultMessage: "Components selected: {count}",
    values: {
      count: /*#__PURE__*/_react.default.createElement("span", {
        className: "componentTemplatesSelector__selection__header__count"
      }, componentsSelected.length)
    }
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "eui-yScrollWithShadows componentTemplatesSelector__selection__content"
  }, /*#__PURE__*/_react.default.createElement(_component_templates_selection.ComponentTemplatesSelection, {
    components: componentsSelected,
    onReorder: onSelectionReorder,
    listItemProps: {
      onViewDetail: component => {
        setSelectedComponent(component.name);
      },
      actions: [{
        label: i18nTexts.icons.remove,
        icon: 'minusInCircle',
        handler: component => {
          setComponentsSelected(prev => {
            return prev.filter(({
              name
            }) => component.name !== name);
          });
        }
      }]
    }
  }))) : /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    textAlign: "center",
    "data-test-subj": "emptyPrompt"
  }, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.componentTemplatesSelector.noComponentSelectedLabel-1",
    defaultMessage: "Add component template building blocks to this template."
  }), /*#__PURE__*/_react.default.createElement("br", null), /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.componentTemplatesSelector.noComponentSelectedLabel-2",
    defaultMessage: "Component templates are applied in the order specified."
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_component_templates.ComponentTemplates, {
    isLoading: isLoading,
    components: components !== null && components !== void 0 ? components : [],
    listItemProps: {
      onViewDetail: component => {
        setSelectedComponent(component.name);
      },
      actions: [{
        label: i18nTexts.icons.select,
        icon: 'plusInCircle',
        handler: component => {
          setComponentsSelected(prev => {
            return [...prev, component];
          });
        }
      }],
      isSelected: component => {
        return componentsSelected.find(({
          name
        }) => component.name === name) !== undefined;
      }
    }
  })));
  if (isLoading) {
    return renderLoading();
  } else if (error) {
    return renderError();
  } else if (hasComponents) {
    return renderSelector();
  }

  // No components: render empty prompt
  const emptyPromptBody = /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    color: "subdued"
  }, /*#__PURE__*/_react.default.createElement("p", null, text !== null && text !== void 0 ? text : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.componentTemplatesSelector.emptyPromptDescription",
    defaultMessage: "Components templates let you save index settings, mappings and aliases and inherit from them in index templates."
  }), /*#__PURE__*/_react.default.createElement("br", null), /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
    href: docUri,
    target: "_blank",
    external: true
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.componentTemplatesSelector.emptyPromptLearnMoreLinkText",
    defaultMessage: "Learn more."
  }))));
  return /*#__PURE__*/_react.default.createElement(_eui.EuiEmptyPrompt, {
    iconType: "managementApp",
    title: /*#__PURE__*/_react.default.createElement("h2", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.componentTemplatesSelector.emptyPromptTitle",
      defaultMessage: "You don\u2019t have any components yet"
    })),
    body: emptyPromptBody,
    actions: showCreateButton ? /*#__PURE__*/_react.default.createElement(_components.CreateButtonPopOver, {
      anchorPosition: "downCenter"
    }) : undefined,
    "data-test-subj": "emptyPrompt"
  });
};
exports.ComponentTemplatesSelector = ComponentTemplatesSelector;