"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MappingsEditor = void 0;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _eui = require("@elastic/eui");
var _components = require("./components");
var _lib = require("./lib");
var _mappings_state_context = require("./mappings_state_context");
var _use_state_listener = require("./use_state_listener");
var _config_context = require("./config_context");
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 MappingsEditor = /*#__PURE__*/_react.default.memo(({
  onChange,
  value,
  docLinks,
  indexSettings,
  esNodesPlugins
}) => {
  const {
    parsedDefaultValue,
    multipleMappingsDeclared
  } = (0, _react.useMemo)(() => {
    const mappingsDefinition = (0, _lib.extractMappingsDefinition)(value);
    if (mappingsDefinition === null) {
      return {
        multipleMappingsDeclared: true
      };
    }
    const {
      _source,
      _meta,
      _routing,
      _size,
      dynamic,
      properties,
      runtime,
      /* eslint-disable @typescript-eslint/naming-convention */
      numeric_detection,
      date_detection,
      dynamic_date_formats,
      dynamic_templates
      /* eslint-enable @typescript-eslint/naming-convention */
    } = mappingsDefinition;
    const parsed = {
      configuration: {
        _source,
        _meta,
        _routing,
        _size,
        dynamic,
        numeric_detection,
        date_detection,
        dynamic_date_formats
      },
      fields: properties,
      templates: {
        dynamic_templates
      },
      runtime
    };
    return {
      parsedDefaultValue: parsed,
      multipleMappingsDeclared: false
    };
  }, [value]);

  /**
   * Hook that will listen to:
   * 1. "value" prop changes in order to reset the mappings editor
   * 2. "state" changes in order to communicate any updates to the consumer
   */
  (0, _use_state_listener.useMappingsStateListener)({
    onChange,
    value: parsedDefaultValue
  });
  const {
    update: updateConfig
  } = (0, _config_context.useConfig)();
  const state = (0, _mappings_state_context.useMappingsState)();
  const [selectedTab, selectTab] = (0, _react.useState)('fields');
  (0, _react.useEffect)(() => {
    if (multipleMappingsDeclared) {
      // We set the data getter here as the user won't be able to make any changes
      onChange({
        getData: () => value,
        validate: () => Promise.resolve(true),
        isValid: true
      });
    }
  }, [multipleMappingsDeclared, onChange, value]);
  (0, _react.useEffect)(() => {
    // Update the the config context so it is available globally (e.g in our Global flyout)
    updateConfig({
      docLinks,
      indexSettings: indexSettings !== null && indexSettings !== void 0 ? indexSettings : {}
    });
  }, [updateConfig, docLinks, indexSettings]);
  const changeTab = async tab => {
    if (selectedTab === 'advanced') {
      // When we navigate away we need to submit the form to validate if there are any errors.
      const {
        isValid: isConfigurationFormValid
      } = await state.configuration.submitForm();
      if (!isConfigurationFormValid) {
        /**
         * Don't navigate away from the tab if there are errors in the form.
         */
        return;
      }
    } else if (selectedTab === 'templates') {
      const {
        isValid: isTemplatesFormValid
      } = await state.templates.submitForm();
      if (!isTemplatesFormValid) {
        return;
      }
    }
    selectTab(tab);
  };
  const tabToContentMap = {
    fields: /*#__PURE__*/_react.default.createElement(_components.DocumentFields, null),
    runtimeFields: /*#__PURE__*/_react.default.createElement(_components.RuntimeFieldsList, null),
    templates: /*#__PURE__*/_react.default.createElement(_components.TemplatesForm, {
      value: state.templates.defaultValue
    }),
    advanced: /*#__PURE__*/_react.default.createElement(_components.ConfigurationForm, {
      value: state.configuration.defaultValue,
      esNodesPlugins: esNodesPlugins
    })
  };
  return /*#__PURE__*/_react.default.createElement("div", {
    "data-test-subj": "mappingsEditor"
  }, multipleMappingsDeclared ? /*#__PURE__*/_react.default.createElement(_components.MultipleMappingsWarning, null) : /*#__PURE__*/_react.default.createElement("div", {
    className: "mappingsEditor"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTabs, null, /*#__PURE__*/_react.default.createElement(_eui.EuiTab, {
    onClick: () => changeTab('fields'),
    isSelected: selectedTab === 'fields',
    "data-test-subj": "formTab"
  }, _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.fieldsTabLabel', {
    defaultMessage: 'Mapped fields'
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiTab, {
    onClick: () => changeTab('runtimeFields'),
    isSelected: selectedTab === 'runtimeFields',
    "data-test-subj": "formTab"
  }, _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.runtimeFieldsTabLabel', {
    defaultMessage: 'Runtime fields'
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiTab, {
    onClick: () => changeTab('templates'),
    isSelected: selectedTab === 'templates',
    "data-test-subj": "formTab"
  }, _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.templatesTabLabel', {
    defaultMessage: 'Dynamic templates'
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiTab, {
    onClick: () => changeTab('advanced'),
    isSelected: selectedTab === 'advanced',
    "data-test-subj": "formTab"
  }, _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.advancedTabLabel', {
    defaultMessage: 'Advanced options'
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "l"
  }), tabToContentMap[selectedTab]));
});
exports.MappingsEditor = MappingsEditor;