"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Form = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _lodash = require("lodash");
var _i18n = require("@kbn/i18n");
var _public = require("@kbn/kibana-react-plugin/public");
var _lib = require("../../lib");
var _field = require("../field");
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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

class Form extends _react.PureComponent {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "state", {
      unsavedChanges: {},
      loading: false
    });
    (0, _defineProperty2.default)(this, "getSettingByKey", key => {
      return Object.values(this.props.settings).flat().find(el => el.name === key);
    });
    (0, _defineProperty2.default)(this, "getCountOfUnsavedChanges", () => {
      return Object.keys(this.state.unsavedChanges).length;
    });
    (0, _defineProperty2.default)(this, "getCountOfHiddenUnsavedChanges", () => {
      const shownSettings = Object.values(this.props.visibleSettings).flat().map(setting => setting.name);
      return Object.keys(this.state.unsavedChanges).filter(key => !shownSettings.includes(key)).length;
    });
    (0, _defineProperty2.default)(this, "areChangesInvalid", () => {
      const {
        unsavedChanges
      } = this.state;
      return Object.values(unsavedChanges).some(({
        isInvalid
      }) => isInvalid);
    });
    (0, _defineProperty2.default)(this, "handleChange", (key, change) => {
      const setting = this.getSettingByKey(key);
      if (!setting) {
        return;
      }
      const {
        type,
        defVal,
        value
      } = setting;
      const savedValue = (0, _field.getEditableValue)(type, value, defVal);
      if (change.value === savedValue) {
        return this.clearChange(key);
      }
      this.setState({
        unsavedChanges: {
          ...this.state.unsavedChanges,
          [key]: change
        }
      });
    });
    (0, _defineProperty2.default)(this, "clearChange", key => {
      if (!this.state.unsavedChanges[key]) {
        return;
      }
      const unsavedChanges = {
        ...this.state.unsavedChanges
      };
      delete unsavedChanges[key];
      this.setState({
        unsavedChanges
      });
    });
    (0, _defineProperty2.default)(this, "clearAllUnsaved", () => {
      this.setState({
        unsavedChanges: {}
      });
    });
    (0, _defineProperty2.default)(this, "saveAll", async () => {
      this.setLoading(true);
      const {
        unsavedChanges
      } = this.state;
      if ((0, _lodash.isEmpty)(unsavedChanges)) {
        return;
      }
      const configToSave = {};
      let requiresReload = false;
      Object.entries(unsavedChanges).forEach(([name, {
        value
      }]) => {
        const setting = this.getSettingByKey(name);
        if (!setting) {
          return;
        }
        const {
          defVal,
          type,
          requiresPageReload,
          metric
        } = setting;
        let valueToSave = value;
        let equalsToDefault = false;
        switch (type) {
          case 'array':
            valueToSave = valueToSave.trim();
            valueToSave = valueToSave === '' ? [] : valueToSave.split(',').map(val => val.trim());
            equalsToDefault = valueToSave.join(',') === defVal.join(',');
            break;
          case 'json':
            const isArray = Array.isArray(JSON.parse(defVal || '{}'));
            valueToSave = valueToSave.trim();
            valueToSave = valueToSave || (isArray ? '[]' : '{}');
          case 'boolean':
            if (metric && this.props.trackUiMetric) {
              const metricName = valueToSave ? `${metric.name}_on` : `${metric.name}_off`;
              this.props.trackUiMetric(metric.type, metricName);
            }
          default:
            equalsToDefault = valueToSave === defVal;
        }
        if (requiresPageReload) {
          requiresReload = true;
        }
        configToSave[name] = equalsToDefault ? null : valueToSave;
      });
      try {
        await this.props.save(configToSave);
        this.clearAllUnsaved();
        if (requiresReload) {
          this.renderPageReloadToast();
        }
      } catch (e) {
        this.props.toasts.addDanger(_i18n.i18n.translate('advancedSettings.form.saveErrorMessage', {
          defaultMessage: 'Unable to save'
        }));
      }
      this.setLoading(false);
    });
    (0, _defineProperty2.default)(this, "renderPageReloadToast", () => {
      this.props.toasts.add({
        title: _i18n.i18n.translate('advancedSettings.form.requiresPageReloadToastDescription', {
          defaultMessage: 'One or more settings require you to reload the page to take effect.'
        }),
        text: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_public.KibanaThemeProvider, {
          theme$: this.props.theme
        }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
          justifyContent: "flexEnd",
          gutterSize: "s"
        }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
          grow: false
        }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
          size: "s",
          onClick: () => window.location.reload(),
          "data-test-subj": "windowReloadButton"
        }, _i18n.i18n.translate('advancedSettings.form.requiresPageReloadToastButtonLabel', {
          defaultMessage: 'Reload page'
        })))))),
        color: 'success'
      });
    });
    (0, _defineProperty2.default)(this, "renderCountOfUnsaved", () => {
      const unsavedCount = this.getCountOfUnsavedChanges();
      const hiddenUnsavedCount = this.getCountOfHiddenUnsavedChanges();
      return /*#__PURE__*/_react.default.createElement(_eui.EuiTextColor, {
        className: "mgtAdvancedSettingsForm__unsavedCountMessage",
        color: "ghost"
      }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "advancedSettings.form.countOfSettingsChanged",
        defaultMessage: "{unsavedCount} unsaved {unsavedCount, plural, one {setting} other {settings} }{hiddenCount, plural, =0 {} other {, # hidden} }",
        values: {
          unsavedCount,
          hiddenCount: hiddenUnsavedCount
        }
      }));
    });
    (0, _defineProperty2.default)(this, "renderBottomBar", () => {
      const areChangesInvalid = this.areChangesInvalid();
      return /*#__PURE__*/_react.default.createElement(_eui.EuiBottomBar, {
        "data-test-subj": "advancedSetting-bottomBar"
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
        justifyContent: "spaceBetween",
        alignItems: "center",
        responsive: false,
        gutterSize: "s"
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false,
        className: "mgtAdvancedSettingsForm__unsavedCount"
      }, /*#__PURE__*/_react.default.createElement("p", {
        id: "aria-describedby.countOfUnsavedSettings"
      }, this.renderCountOfUnsaved())), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
        color: "ghost",
        size: "s",
        iconType: "cross",
        onClick: this.clearAllUnsaved,
        "aria-describedby": "aria-describedby.countOfUnsavedSettings",
        "data-test-subj": "advancedSetting-cancelButton"
      }, _i18n.i18n.translate('advancedSettings.form.cancelButtonLabel', {
        defaultMessage: 'Cancel changes'
      }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
        content: areChangesInvalid && _i18n.i18n.translate('advancedSettings.form.saveButtonTooltipWithInvalidChanges', {
          defaultMessage: 'Fix invalid settings before saving.'
        })
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
        className: "mgtAdvancedSettingsForm__button",
        disabled: areChangesInvalid,
        color: "success",
        fill: true,
        size: "s",
        iconType: "check",
        onClick: this.saveAll,
        "aria-describedby": "aria-describedby.countOfUnsavedSettings",
        isLoading: this.state.loading,
        "data-test-subj": "advancedSetting-saveButton"
      }, _i18n.i18n.translate('advancedSettings.form.saveButtonLabel', {
        defaultMessage: 'Save changes'
      }))))));
    });
  }
  setLoading(loading) {
    this.setState({
      loading
    });
  }
  renderClearQueryLink(totalSettings, currentSettings) {
    const {
      clearQuery
    } = this.props;
    if (totalSettings !== currentSettings) {
      return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement("em", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "advancedSettings.form.searchResultText",
        defaultMessage: "Search terms are hiding {settingsCount} settings {clearSearch}",
        values: {
          settingsCount: totalSettings - currentSettings,
          clearSearch: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
            onClick: clearQuery
          }, /*#__PURE__*/_react.default.createElement("em", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "advancedSettings.form.clearSearchResultText",
            defaultMessage: "(clear search)"
          })))
        }
      })));
    }
    return null;
  }
  renderCategory(category, settings, totalSettings) {
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, {
      key: category
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiSplitPanel.Outer, {
      hasBorder: true
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiSplitPanel.Inner, {
      color: "subdued"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      alignItems: "baseline"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h2", null, (0, _lib.getCategoryName)(category)))), this.renderClearQueryLink(totalSettings, settings.length))), /*#__PURE__*/_react.default.createElement(_eui.EuiSplitPanel.Inner, null, settings.map(setting => {
      return /*#__PURE__*/_react.default.createElement(_field.Field, {
        key: setting.name,
        setting: setting,
        handleChange: this.handleChange,
        unsavedChanges: this.state.unsavedChanges[setting.name],
        clearChange: this.clearChange,
        enableSaving: this.props.enableSaving,
        docLinks: this.props.docLinks,
        toasts: this.props.toasts
      });
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "l"
    }));
  }
  maybeRenderNoSettings(clearQuery) {
    if (this.props.showNoResultsMessage) {
      return /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
        color: "danger",
        title: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "advancedSettings.form.noSearchResultText",
          defaultMessage: "No settings found for {queryText} {clearSearch}",
          values: {
            clearSearch: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
              onClick: clearQuery
            }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
              id: "advancedSettings.form.clearNoSearchResultText",
              defaultMessage: "(clear search)"
            })),
            queryText: /*#__PURE__*/_react.default.createElement("strong", null, this.props.queryText)
          }
        }))
      });
    }
    return null;
  }
  render() {
    const {
      unsavedChanges
    } = this.state;
    const {
      visibleSettings,
      categories,
      categoryCounts,
      clearQuery
    } = this.props;
    const currentCategories = [];
    const hasUnsavedChanges = !(0, _lodash.isEmpty)(unsavedChanges);
    if (hasUnsavedChanges) {
      document.body.classList.add('kbnBody--mgtAdvancedSettingsHasBottomBar');
    } else {
      document.body.classList.remove('kbnBody--mgtAdvancedSettingsHasBottomBar');
    }
    categories.forEach(category => {
      if (visibleSettings[category] && visibleSettings[category].length) {
        currentCategories.push(category);
      }
    });
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement("div", null, currentCategories.length ? currentCategories.map(category => {
      return this.renderCategory(category, visibleSettings[category], categoryCounts[category]);
    }) : this.maybeRenderNoSettings(clearQuery)), hasUnsavedChanges && this.renderBottomBar());
  }
}
exports.Form = Form;