"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.SettingsPageState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _mobx = require("mobx");
var _SettingsPageStateBIReporter = require("./SettingsPageStateBIReporter");
var _events = require("@wix/bex-core/events");
class SettingsPageState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "fetch", void 0);
    (0, _defineProperty2.default)(this, "_onSave", void 0);
    (0, _defineProperty2.default)(this, "_onCancel", void 0);
    (0, _defineProperty2.default)(this, "saveSuccessToast", void 0);
    (0, _defineProperty2.default)(this, "saveErrorToast", void 0);
    (0, _defineProperty2.default)(this, "_settings", null);
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "reportBI", void 0);
    (0, _defineProperty2.default)(this, "bi", void 0);
    (0, _defineProperty2.default)(this, "formPage", void 0);
    (0, _defineProperty2.default)(this, "events", new _events.EventEmitter());
    this.fetch = params.fetch;
    this._onSave = params.onSave;
    this._onCancel = params.onCancel;
    this.saveSuccessToast = params.saveSuccessToast;
    this.saveErrorToast = params.saveErrorToast;
    this.formPage = new _bexCore.FormPageState({
      form: params.form
    });
    this.container = params.container;
    this.reportBI = this.container.createBILogger({
      componentType: 'Settings page',
      pageType: 'Settings',
      route: window.location.pathname
    });
    this.bi = new _SettingsPageStateBIReporter.SettingsPageStateBIReporter({
      reportBI: this.reportBI,
      settingsPageState: this
    });
    this.bi.init();
    (0, _mobx.makeObservable)(this, {
      handleSubmit: _mobx.action,
      _settings: _mobx.observable.ref,
      setSettings: _mobx.action,
      isDirty: _mobx.computed
    });
  }
  init() {
    const {
      formPage: {
        initTask
      },
      container
    } = this;
    const {
      onBeforeUnload
    } = container;
    const onBeforeUnloadSubscription = onBeforeUnload == null ? void 0 : onBeforeUnload((0, _mobx.action)(event => {
      if (!this.isDirty) {
        return;
      }
      event.preventDefault();
      this.bi.reportOnBeforeUnload();
    }));
    initTask.runOnce(async () => {
      var _this$bi$appLoaded, _this$bi;
      const [data] = await Promise.all([this.fetch(), container.initTask.status.promise]);
      this.setSettings(data.settings ?? null);
      (_this$bi$appLoaded = (_this$bi = this.bi).appLoaded) == null || _this$bi$appLoaded.call(_this$bi);
    });
    return () => {
      onBeforeUnloadSubscription == null || onBeforeUnloadSubscription.remove();
    };
  }
  retryFetch() {
    this.formPage.retryFetch();
  }
  setSettings(newSettings) {
    this._settings = newSettings;
  }
  get settings() {
    return this._settings;
  }
  get isFetching() {
    return this.formPage.isFetching;
  }
  get form() {
    return this.formPage.form;
  }
  get isDirty() {
    return this.formPage.isDirty;
  }
  onCancel() {
    this.bi.reportButtonClick({
      ctaName: 'Cancel'
    });
    this._onCancel();
  }
  _showErrorToast(err, e) {
    var _this$saveErrorToast, _this$container$showT, _this$container;
    const errorToast = (_this$saveErrorToast = this.saveErrorToast) == null ? void 0 : _this$saveErrorToast.call(this, err, {
      retry: () => this.handleSubmit(e)
    });
    const message = typeof errorToast === 'string' ? errorToast : errorToast == null ? void 0 : errorToast.message;
    const showTryAgain = typeof errorToast === 'string' ? true : (errorToast == null ? void 0 : errorToast.tryAgain) !== false;
    const action = typeof errorToast === 'string' ? undefined : errorToast == null ? void 0 : errorToast.action;
    (_this$container$showT = (_this$container = this.container).showToast) == null || _this$container$showT.call(_this$container, {
      type: 'ERROR',
      biName: 'cairo-settings-page-save-error-toast',
      message: message ?? this.container.translate((err == null ? void 0 : err.code) === 'ERR_NETWORK' ? 'cairo.entityPage.saveError-offline.toast.description' : 'cairo.entityPage.saveError-technical.toast.description'),
      action: action || showTryAgain ? {
        uiType: 'LINK',
        text: (action == null ? void 0 : action.text) ?? this.container.translate('cairo.toast.retry'),
        onClick: () => {
          if (action != null && action.onClick) {
            action.onClick();
          } else {
            this.bi.reportSaveTryAgain();
            this.handleSubmit(e);
          }
        },
        removeToastOnClick: true
      } : undefined
    });
  }
  _showSuccessToast() {
    var _this$saveSuccessToas, _this$container$showT2, _this$container2;
    const message = typeof this.saveSuccessToast === 'string' ? this.saveSuccessToast : (_this$saveSuccessToas = this.saveSuccessToast) == null ? void 0 : _this$saveSuccessToas.message;
    (_this$container$showT2 = (_this$container2 = this.container).showToast) == null || _this$container$showT2.call(_this$container2, {
      type: 'SUCCESS',
      biName: 'cairo-settings-page-save-success-toast',
      message: message ?? this.container.translate('cairo.entityPage.success.toast')
    });
  }
  async handleSubmit(e) {
    if (this.formPage.submitTask.status.isLoading) {
      return;
    }
    this.events.emit('save');
    const {
      form,
      formPage: {
        submitTask
      },
      bi
    } = this;
    submitTask.run(async () => {
      await form.handleSubmit(async () => {
        bi.reportButtonClick({
          ctaName: 'Save',
          isValid: true
        });
        try {
          if (!this.isFetching) {
            await this._onSave();
            form.reset(form.getValues());
          }
          this._showSuccessToast();
        } catch (err) {
          this._showErrorToast(err, e);
          this.container.errorMonitor.captureException(err);
          this.events.emit('saveError', err);
          form.setError('root.serverError', {}); // https://react-hook-form.com/docs/useform/seterror
        }
      }, () => {
        bi.reportButtonClick({
          ctaName: 'Save',
          isValid: false
        });
      } // can be used to report validation errors
      )(e);
    });
    await this.formPage.submitTask.status.promise;
  }
  get initTask() {
    return this.formPage.initTask;
  }
  get submitTask() {
    return this.formPage.submitTask;
  }
}
exports.SettingsPageState = SettingsPageState;
//# sourceMappingURL=SettingsPageState.js.map