"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.WixPatternsContainerDriver = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _events = require("events");
var _core = require("react-query/core");
var _history = require("history");
var _testkit = require("@wix/fe-essentials-standalone/testkit");
var _react = require("@wix/fe-essentials-standalone/react");
var _client = require("@wix/fe-essentials/http-client/testkit/client");
var _dataCapsule = require("@wix/fe-essentials/data-capsule");
var _state = require("../state");
var _partialLodashMock = require("../mocks/partialLodashMock");
var _lodash = require("lodash");
var _exportServiceMocks = require("./exportServiceMocks");
var _navigationManager = require("../services/navigationManager");
var _matchMediaMock = require("./matchMediaMock");
var _jest = require("../test-utils/jest");
var _appSettingsMocks = require("./appSettingsMocks");
var _errorHandler = require("@wix/fe-essentials/error-handler");
class WixPatternsContainerDriver {
  get tableDataCapsule() {
    return this.dataCapsuleInstances.get('cairo.cairo-test-component.wix.cairo.products.v1.product');
  }
  constructor(overrides = {
    asMobileView: false,
    contextType: 'SITE'
  }) {
    var _overrides$history, _overrides$i18nOverri, _overrides$i18nOverri2;
    (0, _defineProperty2.default)(this, "testContext", void 0);
    (0, _defineProperty2.default)(this, "showToast", void 0);
    (0, _defineProperty2.default)(this, "usePageLocation", void 0);
    (0, _defineProperty2.default)(this, "navigateTo", void 0);
    (0, _defineProperty2.default)(this, "onNavigation", void 0);
    (0, _defineProperty2.default)(this, "onBeforeUnload", void 0);
    (0, _defineProperty2.default)(this, "onLayerStateChange", void 0);
    (0, _defineProperty2.default)(this, "onlineManager", {
      _events: new _events.EventEmitter(),
      _isOnline: true,
      setIsOnline(value) {
        this._isOnline = value;
        this._events.emit('default');
      },
      isOnline() {
        return this._isOnline;
      },
      subscribe(listener) {
        if (listener) {
          this._events.on('default', listener);
        }
        return () => {
          if (listener) {
            this._events.removeListener('default', listener);
          }
        };
      }
    });
    (0, _defineProperty2.default)(this, "focusManager", {
      _events: new _events.EventEmitter(),
      _isFocused: true,
      setIsFocused(value) {
        this._isFocused = value;
        this._events.emit('default');
      },
      isFocused() {
        return this._isFocused;
      },
      subscribe(listener) {
        if (listener) {
          this._events.on('default', listener);
        }
        return () => {
          if (listener) {
            this._events.removeListener('default', listener);
          }
        };
      }
    });
    (0, _defineProperty2.default)(this, "queryCache", new _core.QueryCache());
    (0, _defineProperty2.default)(this, "patchesCache", new Map());
    (0, _defineProperty2.default)(this, "window", void 0);
    (0, _defineProperty2.default)(this, "navigationManager", void 0);
    (0, _defineProperty2.default)(this, "history", void 0);
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "dataCapsule", []);
    (0, _defineProperty2.default)(this, "dataCapsuleInstances", new Map());
    (0, _defineProperty2.default)(this, "componentSettingsInstances", new Map());
    (0, _defineProperty2.default)(this, "exportServiceMocks", void 0);
    this.exportServiceMocks = (0, _exportServiceMocks.exportServiceMocks)(_client.whenRequest);
    this.testContext = _testkit.testkit.getTestContext({
      experiments: {
        bag: overrides.experiments
      },
      environment: {
        language: 'en',
        ...(overrides == null ? void 0 : overrides.environment)
      },
      i18n: {
        messages: language => require(`../assets/locale/messages_${language}.json`)
      },
      errorMonitor: {},
      httpClient: {
        scenarios: [
        /* metro-testkit currently takes the first mock it encounters per API,
        so overrides must be added before appSettingsMocks(whenRequest) */
        ...(overrides.appSettingsCustomMocks ?? []), ...(0, _appSettingsMocks.appSettingsMocks)(_client.whenRequest), ...this.exportServiceMocks.mocks, ...(overrides.httpMocks ?? [])]
      }
    });
    this.testContext.essentials._parent.environment.artifactId = 'cairo';
    const {
      asyncExperiments
    } = overrides;
    if (asyncExperiments) {
      this.testContext.experiments.ready = async () => {
        await asyncExperiments();
      };
    }
    this.window = {
      location: {
        href: 'https://cairo.test',
        ...overrides.location
      },
      download: jest.fn(),
      matchMedia: jest.fn().mockImplementation(query => ({
        ...(0, _matchMediaMock.matchMediaMock)(query),
        matches: !overrides.asMobileView
      })),
      close: () => {
        window.dispatchEvent(new Event('beforeunload'));
        window.dispatchEvent(new Event('unload'));
      }
    };
    this.navigationManager = new _navigationManager.NavigationManager(this.window);
    this.showToast = (overrides == null ? void 0 : overrides.showToast) ?? jest.fn().mockImplementation(() => ({
      remove: () => {}
    }));
    this.usePageLocation = overrides.usePageLocation ?? jest.fn();
    this.navigateTo = (overrides == null ? void 0 : overrides.navigateTo) ?? jest.fn();
    this.onLayerStateChange = (overrides == null ? void 0 : overrides.onLayerStateChange) ?? jest.fn().mockReturnValue({
      remove: () => {}
    });
    this.onNavigation = (overrides == null ? void 0 : overrides.onNavigation) ?? jest.fn().mockImplementation(callback => {
      const remove = this.navigationManager.subscribe(state => {
        state.prevented = true;
        callback(state.pause);
      });
      return {
        remove
      };
    });
    if (!overrides.onBeforeUnloadMissingInEnvironment) {
      this.onBeforeUnload = (overrides == null ? void 0 : overrides.onBeforeUnload) ?? jest.fn().mockImplementation(callback => {
        const remove = this.navigationManager.subscribe(state => {
          const {
            resume
          } = state.pause();
          callback({
            preventDefault: () => {
              state.prevented = true;
              this.navigationManager.events.once('navigationPromptResult', leave => {
                if (leave) {
                  resume();
                }
              });
            }
          });
        });
        return {
          remove
        };
      });
    }
    this.history = overrides.historyInstance || (0, _history.createMemoryHistory)();
    if (overrides != null && (_overrides$history = overrides.history) != null && _overrides$history.search) {
      this.replaceHistory(overrides.history.search);
    }
    this.container = new _state.WixPatternsContainer({
      queryCache: this.queryCache,
      patchesCache: this.patchesCache,
      errorMonitor: this.testContext.errorMonitor,
      errorHandler: !overrides.noErrorHandler ? new _errorHandler.ErrorHandler({
        biLoggerOrFactory: this.testContext.asPartial.biLogger ?? this.testContext.biLoggerFactory,
        createErrorMonitor: options => this.testContext.createChildEssentials({
          errorMonitor: options
        }).errorMonitor,
        environment: this.testContext.environment,
        createI18n: options => this.testContext.createChildEssentials({
          i18n: options
        }).i18n
      }).v2 : undefined,
      history: this.history,
      contextType: overrides.contextType,
      environment: {
        ...this.testContext.environment,
        ...(overrides == null ? void 0 : overrides.environment),
        componentId: [this.testContext.environment.artifactId, 'cairo-test-component'].join('.'),
        providerType: 'bm'
      },
      environmentBI: {
        artifactId: this.testContext.environment.artifactId
      },
      user: {
        permissions: [],
        ...(overrides == null ? void 0 : overrides.user)
      },
      httpClient: this.testContext.httpClient,
      experiments: this.testContext.experiments,
      onlineManager: this.onlineManager,
      focusManager: this.focusManager,
      window: this.window,
      useTranslation: _react.useTranslation,
      Trans: _react.Trans,
      useExperiments: _react.useExperiments,
      createComponentSettings: overrides.componentSettingsLocalStorage ? undefined : () => ({
        namespace
      }) => {
        var _overrides$componentS;
        const componentSettings = new _dataCapsule.DataCapsule({
          namespace,
          scope: '',
          strategy: new _dataCapsule.AppSettingsStorageStrategy({
            host: 'other',
            httpClient: this.testContext.httpClient
          })
        });
        const data = (_overrides$componentS = overrides.componentSettingsEntries) == null ? void 0 : _overrides$componentS[namespace];
        if (data) {
          for (const [key, value] of Object.entries(data)) {
            componentSettings.setItem(key, value);
          }
        }
        this.componentSettingsInstances.set(namespace, componentSettings);
        return componentSettings;
      },
      messagesEnImport: (_overrides$i18nOverri = overrides.i18nOverrides) == null ? void 0 : _overrides$i18nOverri.messagesEnImport,
      fetchTranslations: (_overrides$i18nOverri2 = overrides.i18nOverrides) == null ? void 0 : _overrides$i18nOverri2.fetchTranslations,
      createEssentials: options => {
        const i18nOptions = options.i18n;
        const childEssentials = this.testContext.createChildEssentials({
          ...options,
          ...(i18nOptions && {
            i18n: {
              ...i18nOptions,
              asyncMessagesLoader: locale => {
                var _overrides$i18nOverri3;
                return Promise.all([(i18nOptions.asyncMessagesLoader == null ? void 0 : i18nOptions.asyncMessagesLoader(locale)) ?? {}, ((_overrides$i18nOverri3 = overrides.i18nOverrides) == null || _overrides$i18nOverri3.asyncMessagesLoader == null ? void 0 : _overrides$i18nOverri3.asyncMessagesLoader(locale)) ?? {}]).then(messages => messages.reduce(Object.assign, {}));
              }
            }
          }),
          ...(options.experiments && {
            experiments: {
              bag: {
                'specs.os.EnableErrorHandlerInEditor': 'true',
                ...('bag' in options.experiments ? options.experiments.bag : undefined),
                ...overrides.internalExperiments
              }
            }
          })
        });
        if (options.dataCapsule && childEssentials.dataCapsule) {
          this.dataCapsule.push(childEssentials.dataCapsule);
          this.dataCapsuleInstances.set(options.dataCapsule.namespace, childEssentials.dataCapsule);
          for (const [key, value] of Object.entries(((_overrides$dataCapsul = overrides.dataCapsule) == null ? void 0 : _overrides$dataCapsul.entries) ?? {})) {
            var _overrides$dataCapsul;
            childEssentials.dataCapsule.setItem(key, value);
          }
        }
        return childEssentials;
      },
      showToast: this.showToast,
      usePageLocation: this.usePageLocation,
      navigateTo: to => {
        var _this$navigateTo;
        (_this$navigateTo = this.navigateTo) == null || _this$navigateTo.call(this, to);
        this.navigationManager.navigateToPage(to);
      },
      onNavigation: this.onNavigation,
      onBeforeUnload: this.onBeforeUnload,
      onLayerStateChange: this.onLayerStateChange,
      openMediaManager: overrides == null ? void 0 : overrides.openMediaManager,
      getHostContainer: overrides == null ? void 0 : overrides.getHostContainer,
      lodash: (0, _jest.isTestEnvironment)() && (0, _jest.isJestExists)() && jest.isMockFunction(setTimeout) ? (0, _partialLodashMock.partialLodashMock)() : {
        debounce: _lodash.debounce,
        throttle: _lodash.throttle
      }
    });
    this.container.init();
  }
  get errorMonitor() {
    return this.testContext.errorMonitor;
  }
  get errorHandler() {
    return this.container.errorHandler;
  }
  get i18n() {
    return this.container.i18n;
  }
  get onlineState() {
    return this.container.onlineState;
  }
  get environment() {
    return this.container.environment;
  }
  get environmentBI() {
    return this.container.environmentBI;
  }
  get getHostContainer() {
    return this.container.getHostContainer;
  }
  get biLoggerFactory() {
    return this.testContext.biLoggerFactory;
  }
  replaceHistory(searchParams) {
    const search = searchParams.toString();
    this.history.replace({
      ...this.history.location,
      search: search ? `?${search}` : ''
    });
  }
}
exports.WixPatternsContainerDriver = WixPatternsContainerDriver;
//# sourceMappingURL=WixPatternsContainer.driver.js.map