"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.EntityPageState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _mobx = require("mobx");
var _EntityPageStateBIReporter = require("./EntityPageStateBIReporter");
var _events = require("@wix/bex-core/events");
class EntityPageState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "fetch", void 0);
    (0, _defineProperty2.default)(this, "onSave", void 0);
    (0, _defineProperty2.default)(this, "saveSuccessToast", void 0);
    (0, _defineProperty2.default)(this, "saveErrorToast", void 0);
    (0, _defineProperty2.default)(this, "transformEntityToCollectionItem", void 0);
    (0, _defineProperty2.default)(this, "_entity", null);
    (0, _defineProperty2.default)(this, "_parentPageId", void 0);
    (0, _defineProperty2.default)(this, "_parentPath", void 0);
    (0, _defineProperty2.default)(this, "actionsBarConfig", void 0);
    (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, "_routerState", null);
    (0, _defineProperty2.default)(this, "formPage", void 0);
    (0, _defineProperty2.default)(this, "events", new _events.EventEmitter());
    this.fetch = params.fetch;
    this.onSave = params.onSave;
    this.saveSuccessToast = params.saveSuccessToast;
    this.saveErrorToast = params.saveErrorToast;
    this.formPage = new _bexCore.FormPageState({
      form: params.form
    });
    this._parentPageId = params.parentPageId;
    this.transformEntityToCollectionItem = params.transformEntityToCollectionItem || (anEntity => anEntity);
    this._parentPath = params.parentPath;
    this.container = params.container;
    this._routerState = params.routerState ?? null;
    if (this._routerState) {
      var _this$_routerState$cu;
      this._entity = (_this$_routerState$cu = this._routerState.currentState) == null || (_this$_routerState$cu = _this$_routerState$cu._chosenEntity) == null ? void 0 : _this$_routerState$cu.entity;
    }
    this.reportBI = this.container.createBILogger({
      componentType: 'Entity page',
      pageType: 'Entity',
      route: window.location.pathname
    });
    this.bi = new _EntityPageStateBIReporter.EntityPageStateBIReporter({
      reportBI: this.reportBI,
      entityPageState: this
    });
    this.bi.init();
    (0, _mobx.makeObservable)(this, {
      handleSubmit: _mobx.action,
      _entity: _mobx.observable.ref,
      setEntity: _mobx.action,
      isFormDirty: _mobx.computed,
      _withinRouter: _mobx.computed
    });
  }
  init() {
    this._checkPageParams();
    const {
      formPage: {
        initTask
      },
      container
    } = this;
    const {
      onBeforeUnload
    } = container;
    const onBeforeUnloadSubscription = onBeforeUnload == null ? void 0 : onBeforeUnload((0, _mobx.action)(event => {
      if ((0, _bexCore.isMobileDevice)()) {
        return;
      }
      const {
        form
      } = this;
      // Check both react-hook-form's state AND the explicitly set flag
      if (form.formState.isSubmitSuccessful || this.formPage._isSubmitSuccessful || !this.isFormDirty) {
        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.setEntity(data.entity ?? 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();
  }
  setEntity(newEntity) {
    this._entity = newEntity;
  }
  get entity() {
    return this._entity;
  }
  get isFetching() {
    return this.formPage.isFetching;
  }
  get form() {
    return this.formPage.form;
  }
  set isSubmitSuccessful(flag) {
    this.formPage.isSubmitSuccessful = flag;
  }
  get isFormDirty() {
    return this.formPage.isDirty;
  }

  // backwards compatibility
  set _isFormDirty(val) {
    this.formPage._isFormDirty = val;
  }
  get _withinRouter() {
    return !!this._routerState;
  }
  onCancel() {
    var _this$actionsBarConfi;
    this.bi.reportButtonClick({
      ctaName: 'Cancel',
      additionalInfo: (_this$actionsBarConfi = this.actionsBarConfig) == null || (_this$actionsBarConfi = _this$actionsBarConfi.cancelCta) == null ? void 0 : _this$actionsBarConfi.biAdditionalInfo
    });
    this.navigateToParent();
  }
  navigateToParent(updatedEntity) {
    const entityStringKey = this._entity ? '_updatedEntity' : '_createdEntity';
    const entityObject = {
      [entityStringKey]: updatedEntity
    };
    if (this._withinRouter) {
      this._routerState.navigate(this._parentPath, {
        state: entityObject
      });
    } else {
      this.container.navigateTo({
        pageId: this._parentPageId
      });
    }
  }
  _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-entity-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-entity-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 {
      isValid,
      data: widgetsFormData
    } = await this.formPage.validate();
    if (!isValid) {
      var _this$actionsBarConfi2;
      this.bi.reportButtonClick({
        ctaName: 'Save',
        isValid: false,
        additionalInfo: (_this$actionsBarConfi2 = this.actionsBarConfig) == null || (_this$actionsBarConfi2 = _this$actionsBarConfi2.saveCta) == null ? void 0 : _this$actionsBarConfi2.biAdditionalInfo
      });
      return;
    }
    const {
      form,
      formPage: {
        submitTask
      },
      bi
    } = this;
    submitTask.run(async () => {
      let savedEntity;
      let submitSuccessful = false;
      await form.handleSubmit(async () => {
        var _this$actionsBarConfi3;
        bi.reportButtonClick({
          ctaName: 'Save',
          isValid: true,
          additionalInfo: (_this$actionsBarConfi3 = this.actionsBarConfig) == null || (_this$actionsBarConfi3 = _this$actionsBarConfi3.saveCta) == null ? void 0 : _this$actionsBarConfi3.biAdditionalInfo
        });
        try {
          if (!this.isFetching) {
            const onSaveResult = await this.onSave({
              widgetsFormData
            });
            savedEntity = onSaveResult == null ? void 0 : onSaveResult.updatedEntity;
          }
          this._showSuccessToast();
          submitSuccessful = true; // Mark as successful locally
          // Explicitly set isSubmitSuccessful to prevent onBeforeUnload from triggering
          this.isSubmitSuccessful = true;
        } 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
        }
      }, () => {
        var _this$actionsBarConfi4;
        bi.reportButtonClick({
          ctaName: 'Save',
          isValid: false,
          additionalInfo: (_this$actionsBarConfi4 = this.actionsBarConfig) == null || (_this$actionsBarConfi4 = _this$actionsBarConfi4.saveCta) == null ? void 0 : _this$actionsBarConfi4.biAdditionalInfo
        });
      } // can be used to report validation errors
      )(e);
      if (!submitSuccessful) {
        return;
      }
      const transformedItem = savedEntity && this.transformEntityToCollectionItem ? this.transformEntityToCollectionItem(savedEntity) : savedEntity;
      this.navigateToParent(transformedItem);
    });
    await this.formPage.submitTask.status.promise;
  }
  get initTask() {
    return this.formPage.initTask;
  }
  get submitTask() {
    return this.formPage.submitTask;
  }
  _checkPageParams() {
    if (this._withinRouter) {
      if (this._parentPath === undefined) {
        throw new Error('parentPath was not defined in useEntityPage');
      }
    } else {
      if (this._parentPageId === undefined) {
        throw new Error('parentPageId was not defined in useEntityPage');
      }
      if (!this.container.navigateTo) {
        throw new Error('navigateTo was not defined in Patterns Provider');
      }
    }
  }
}
exports.EntityPageState = EntityPageState;
//# sourceMappingURL=EntityPageState.js.map