"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.ViewsHistoryState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _bexCore = require("@wix/bex-core");
class ViewsHistoryState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "views", void 0);
    (0, _defineProperty2.default)(this, "history", void 0);
    (0, _defineProperty2.default)(this, "viewIdSearchParamName", 'viewId');
    (0, _defineProperty2.default)(this, "init", (0, _mobx.action)(() => {
      const {
        views,
        history
      } = this;
      const disposers = [(0, _mobx.reaction)(() => views.currentView, currentView => {
        (0, _bexCore.replaceSearchParamsWith)(history, searchParams => {
          if (currentView) {
            searchParams.set(this.viewIdSearchParamName, currentView.id);
          } else {
            searchParams.delete(this.viewIdSearchParamName);
          }
        });
      }, {
        fireImmediately: true
      })];
      return () => {
        disposers.forEach(d => d());
      };
    }));
    this.views = params.views;
    this.history = params.history;
    this._preInitHistoryPersistence();
  }
  _preInitHistoryPersistence() {
    const {
      history,
      views
    } = this;
    const searchParams = new URLSearchParams(history.location.search);
    const viewIdFromUrl = searchParams.get(this.viewIdSearchParamName);
    if (viewIdFromUrl) {
      views._initialViewIdFromUrl = viewIdFromUrl;
    }
  }
}
exports.ViewsHistoryState = ViewsHistoryState;
//# sourceMappingURL=ViewsHistoryState.js.map