"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DetailsPageSettingsContent = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _react2 = require("@emotion/react");
var _lodash = _interopRequireDefault(require("lodash"));
var _i18nReact = require("@kbn/i18n-react");
var _i18n = require("@kbn/i18n");
var _public = require("@kbn/kibana-react-plugin/public");
var _services = require("../../../../services");
var _notification = require("../../../../services/notification");
var _flatten_object = require("../../../../lib/flatten_object");
var _edit_settings = require("../../../../lib/edit_settings");
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 getEditableSettings = (data, isIndexOpen) => {
  const {
    defaults,
    settings
  } = data;
  // settings user has actually set
  const flattenedSettings = (0, _flatten_object.flattenObject)(settings);
  // settings with their defaults
  const flattenedDefaults = (0, _flatten_object.flattenObject)(defaults);
  const filteredDefaults = _lodash.default.pick(flattenedDefaults, _edit_settings.settingsToDisplay);
  const newSettings = {
    ...filteredDefaults,
    ...flattenedSettings
  };
  // store these to be used as autocomplete values later
  _edit_settings.readOnlySettings.forEach(e => delete newSettings[e]);
  // can't change codec on open index
  if (isIndexOpen) {
    delete newSettings['index.codec'];
  }
  const settingsString = JSON.stringify(newSettings, null, 2);
  return {
    originalSettings: newSettings,
    settingsString
  };
};
const DetailsPageSettingsContent = ({
  isIndexOpen,
  data,
  indexName,
  reloadIndexSettings
}) => {
  const [isEditMode, setIsEditMode] = (0, _react.useState)(false);
  const onEditModeChange = event => {
    setUpdateError(null);
    setIsEditMode(event.target.checked);
  };
  const {
    originalSettings,
    settingsString
  } = getEditableSettings(data, isIndexOpen);
  const [editableSettings, setEditableSettings] = (0, _react.useState)(settingsString);
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [updateError, setUpdateError] = (0, _react.useState)(null);
  const resetChanges = (0, _react.useCallback)(() => {
    setUpdateError(null);
    setEditableSettings(settingsString);
  }, [settingsString]);
  const updateSettings = (0, _react.useCallback)(async () => {
    setUpdateError(null);
    setIsLoading(true);
    try {
      const editedSettings = JSON.parse(editableSettings);
      // don't set if the values have not changed
      Object.keys(originalSettings).forEach(key => {
        if (_lodash.default.isEqual(originalSettings[key], editedSettings[key])) {
          delete editedSettings[key];
        }
      });
      if (Object.keys(editedSettings).length !== 0) {
        const {
          error
        } = await (0, _services.updateIndexSettings)(indexName, editedSettings);
        if (error) {
          setIsLoading(false);
          setUpdateError(error);
        } else {
          setIsLoading(false);
          setIsEditMode(false);
          _notification.notificationService.showSuccessToast(_i18n.i18n.translate('xpack.idxMgmt.indexDetails.settings.updateSuccessMessage', {
            defaultMessage: 'Successfully updated settings for index {indexName}',
            values: {
              indexName
            }
          }));
          reloadIndexSettings();
        }
      } else {
        setIsLoading(false);
        setIsEditMode(false);
        _notification.notificationService.showWarningToast(_i18n.i18n.translate('xpack.idxMgmt.indexDetails.settings.noChangeWarning', {
          defaultMessage: 'No settings changed'
        }));
      }
    } catch (e) {
      setIsLoading(false);
      setUpdateError({
        error: _i18n.i18n.translate('xpack.idxMgmt.indexDetails.settings.updateError', {
          defaultMessage: 'Unable to update settings'
        })
      });
    }
  }, [originalSettings, editableSettings, indexName, reloadIndexSettings]);
  return (
    /*#__PURE__*/
    // using "rowReverse" to keep the card on the left side to be on top of the code block on smaller screens
    _react.default.createElement(_eui.EuiFlexGroup, {
      wrap: true,
      direction: "rowReverse",
      css: (0, _react2.css)`
        height: 100%;
      `
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: 1,
      css: (0, _react2.css)`
          min-width: 400px;
        `
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
      grow: false,
      paddingSize: "l"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      alignItems: "center",
      gutterSize: "s"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      type: "pencil"
    })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement("b", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.indexDetails.settings.docsCardTitle",
      defaultMessage: "Edit index settings"
    }))))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiSwitch, {
      "data-test-subj": "indexDetailsSettingsEditModeSwitch",
      label: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.idxMgmt.indexDetails.settings.editModeSwitchLabel",
        defaultMessage: "Edit mode"
      }),
      checked: isEditMode,
      onChange: onEditModeChange
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: 1
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
      "data-test-subj": "indexDetailsSettingsSave",
      fill: true,
      isDisabled: !isEditMode || !editableSettings || settingsString === editableSettings,
      isLoading: isLoading,
      onClick: updateSettings
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.indexDetails.settings.saveButtonLabel",
      defaultMessage: "Save changes"
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: 1
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
      "data-test-subj": "indexDetailsSettingsResetChanges",
      isDisabled: !isEditMode || isLoading || settingsString === editableSettings,
      onClick: resetChanges
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.indexDetails.settings.resetChangesButtonLabel",
      defaultMessage: "Reset changes"
    })))), updateError && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
      title: _i18n.i18n.translate('xpack.idxMgmt.indexDetails.settings.saveSettingsErrorMessage', {
        defaultMessage: 'Unable to save settings'
      }),
      color: "danger",
      iconType: "error"
    }, updateError.message && /*#__PURE__*/_react.default.createElement("p", null, updateError.message))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
      "data-test-subj": "indexDetailsSettingsDocsLink",
      href: _services.documentationService.getSettingsDocumentationLink(),
      target: "_blank",
      external: true
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.indexDetails.settings.docsCardLink",
      defaultMessage: "Learn more about settings"
    })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: 3,
      css: (0, _react2.css)`
          min-width: 600px;
        `
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, null, isEditMode ? /*#__PURE__*/_react.default.createElement(_public.CodeEditor, {
      languageId: "json",
      value: editableSettings,
      "data-test-subj": "indexDetailsSettingsEditor",
      options: {
        lineNumbers: 'off',
        tabSize: 2,
        automaticLayout: true
      },
      "aria-label": _i18n.i18n.translate('xpack.idxMgmt.formWizard.stepSettings.fieldIndexSettingsAriaLabel', {
        defaultMessage: 'Index settings editor'
      }),
      onChange: setEditableSettings
    }) : /*#__PURE__*/_react.default.createElement(_eui.EuiCodeBlock, {
      language: "json",
      isCopyable: true,
      "data-test-subj": "indexDetailsSettingsCodeBlock",
      css: (0, _react2.css)`
                height: 100%;
              `
    }, JSON.stringify(data, null, 2)))))
  );
};
exports.DetailsPageSettingsContent = DetailsPageSettingsContent;