"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.WixPatternsContainer = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _services = require("../services");
var _model = require("../model");
var _mobx = require("mobx");
var _TaskState = require("./TaskState");
var _OnlineState = require("./OnlineState");
var _createComponentSettings = require("../services/createComponentSettings");
var _ConditionalModalState = require("./ConditionalModalState");
var _events = require("events");
var _util = require("../util");
var _useExperimentsCompat = require("./useExperimentsCompat");
var _uuid = require("uuid");
var _BeforeUnloadCompatState = require("./BeforeUnloadCompatState");
class WixPatternsContainer {
  constructor(params) {
    var _params$initialProps;
    (0, _defineProperty2.default)(this, "createEssentials", void 0);
    (0, _defineProperty2.default)(this, "errorMonitor", void 0);
    (0, _defineProperty2.default)(this, "errorHandler", void 0);
    (0, _defineProperty2.default)(this, "internalMonitor", void 0);
    (0, _defineProperty2.default)(this, "internalExperiments", void 0);
    (0, _defineProperty2.default)(this, "experiments", void 0);
    (0, _defineProperty2.default)(this, "httpClient", void 0);
    (0, _defineProperty2.default)(this, "onlineManager", void 0);
    (0, _defineProperty2.default)(this, "focusManager", void 0);
    (0, _defineProperty2.default)(this, "contextType", void 0);
    (0, _defineProperty2.default)(this, "history", void 0);
    (0, _defineProperty2.default)(this, "window", void 0);
    (0, _defineProperty2.default)(this, "useTranslation", void 0);
    (0, _defineProperty2.default)(this, "Trans", void 0);
    (0, _defineProperty2.default)(this, "useExperiments", 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, "openMediaManager", void 0);
    (0, _defineProperty2.default)(this, "getHostContainer", void 0);
    (0, _defineProperty2.default)(this, "environment", void 0);
    (0, _defineProperty2.default)(this, "environmentBI", void 0);
    (0, _defineProperty2.default)(this, "appendModalsToBody", void 0);
    (0, _defineProperty2.default)(this, "layoutType", void 0);
    (0, _defineProperty2.default)(this, "_useRelativeSidePanel", void 0);
    (0, _defineProperty2.default)(this, "onSidePanelOpen", void 0);
    (0, _defineProperty2.default)(this, "closeSidePanel", void 0);
    (0, _defineProperty2.default)(this, "translate", void 0);
    (0, _defineProperty2.default)(this, "lodash", void 0);
    (0, _defineProperty2.default)(this, "i18n", void 0);
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "_messagesEnImport", void 0);
    (0, _defineProperty2.default)(this, "_fetchTranslations", void 0);
    (0, _defineProperty2.default)(this, "queryCache", void 0);
    (0, _defineProperty2.default)(this, "patchesCache", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _TaskState.TaskState());
    (0, _defineProperty2.default)(this, "onlineState", void 0);
    (0, _defineProperty2.default)(this, "onNavigationModal", void 0);
    (0, _defineProperty2.default)(this, "events", void 0);
    (0, _defineProperty2.default)(this, "user", void 0);
    (0, _defineProperty2.default)(this, "cairoSessionId", void 0);
    (0, _defineProperty2.default)(this, "biLogger", void 0);
    (0, _defineProperty2.default)(this, "createComponentSettings", void 0);
    (0, _defineProperty2.default)(this, "enableTranslatedKeySuffix", void 0);
    (0, _defineProperty2.default)(this, "_isAutoPatterns", false);
    (0, _defineProperty2.default)(this, "createBILogger", defaultParams => {
      return reportProps => {
        const {
          environment,
          environmentBI,
          cairoSessionId,
          biLogger,
          user
        } = this;
        const {
          params: {
            url,
            ...rest
          }
        } = reportProps;
        return biLogger == null ? void 0 : biLogger.report({
          ...reportProps,
          params: {
            ...(environment.msid && {
              msid: environment.msid
            }),
            ...(user.id && {
              uuid: user.id
            }),
            artifactId: environment.artifactId,
            artifactIdNew: environmentBI.artifactId,
            componentName: environment.componentName,
            componentIdNew: environmentBI.componentId,
            cairoVersion: environment.uiLibVersion,
            csid: cairoSessionId,
            ...(environment.providerType === 'bm' && {
              _hostingPlatform: 'business-manager'
            }),
            isAutoPatterns: this._isAutoPatterns,
            ...defaultParams,
            ...(url && {
              url: (0, _util.fixDomainForBI)(url)
            }),
            ...rest
          }
        });
      };
    });
    this.createEssentials = params.createEssentials;
    this.lodash = params.lodash;
    this.patchesCache = params.patchesCache;
    this.events = params.events ?? new _events.EventEmitter();
    this._messagesEnImport = params.messagesEnImport ?? _services.messagesEnImportGlobal;
    this._fetchTranslations = params.fetchTranslations ?? _services.fetchTranslations;
    this.onNavigationModal = params.onNavigationModal ?? new _ConditionalModalState.ConditionalModalState();
    this.environment = (0, _model.wixPatternsEnvironment)(params.environment);
    this.environmentBI = params.environmentBI;
    this.user = params.user;
    this.contextType = params.contextType ?? 'SITE';
    this.createComponentSettings = params.createComponentSettings ?? _createComponentSettings.createComponentSettings;
    this.errorMonitor = params.errorMonitor;
    this.errorHandler = params.errorHandler ?? {
      withErrorHandler: fn => fn(),
      getResolvedError: () => {
        const {
          translate: t
        } = this;
        return {
          message: t('cairo.technical.error.text')
        };
      },
      showError: () => {
        var _this$showToast;
        const {
          translate: t
        } = this;
        (_this$showToast = this.showToast) == null || _this$showToast.call(this, {
          message: t('cairo.technical.error.text'),
          type: 'ERROR'
        });
      }
    };
    this.httpClient = params.httpClient;
    this.onlineManager = params.onlineManager;
    this.focusManager = params.focusManager;
    this.history = params.history;
    this.useTranslation = params.useTranslation;
    this.useExperiments = (0, _useExperimentsCompat.createUseExperimentsCompat)(params.useExperiments);
    this.experiments = params.experiments;
    this.showToast = params.showToast;
    this.usePageLocation = params.usePageLocation;
    this.navigateTo = params.navigateTo;
    this.onNavigation = params.onNavigation;
    this.getHostContainer = params.getHostContainer;
    this.window = params.window;
    this.queryCache = params.queryCache;
    this.appendModalsToBody = params.appendModalsToBody;
    this.layoutType = params.layoutType;
    this._useRelativeSidePanel = params.useRelativeSidePanel;
    this.onSidePanelOpen = params.onSidePanelOpen;
    this.closeSidePanel = params.closeSidePanel;
    this.onBeforeUnload = params.onBeforeUnload;
    this.onLayerStateChange = params.onLayerStateChange;
    this.openMediaManager = params.openMediaManager;
    const {
      i18n,
      biLoggerFactory,
      fedopsLogger: internalFedops,
      errorMonitor: internalErrorMonitor,
      experiments: internalExperiments
    } = this.createEssentials({
      i18n: {
        useSuspense: false,
        disableAutoInit: true,
        asyncMessagesLoader: async locale => {
          if (locale === 'en') {
            return this._messagesEnImport();
          }
          return this._fetchTranslations(this)(locale);
        },
        messages: (_params$initialProps = params.initialProps) == null ? void 0 : _params$initialProps.messages
      },
      errorMonitor: {
        dsn: process.env.NODE_ENV === 'production' ? 'https://9b9586a905eb429cbda9ea49d5d721f6@sentry-next.wixpress.com/8780' : ''
        /*
        TODO: not used in sentry-next API, need to be merged from reportError API with tags & extraData
        For Example: errorMonitor.captureException(error, { tags, contexts: { runtime: extraData }})
        beforeSend: (event, hint) => {
          this.internalMonitor.reportErrorThrownOncePerFlow();
           if (!event.tags) {
            event.tags = {};
          }
           if (!event.extra) {
            event.extra = {};
          }
           if (hint && hint.originalException) {
            event.extra.exception = hint.originalException;
             if (hint.originalException instanceof Error) {
              event.fingerprint = [
                `${hint.originalException.name}:${hint.originalException.message}`,
              ];
            }
          }
           event.tags.componentName = this.environment.componentName;
          event.tags.componentId = this.environment.componentId;
          event.tags.artifactId = this.environment.artifactId;
          event.tags.cairoVersion = this.environment.uiLibVersion;
           return event;
        },
        */
      },
      fedops: {
        appName: 'cairo'
      },
      experiments: {
        scopes: ['cairo']
      }
    });
    if (typeof process !== 'undefined' && process.env.STORYBOOK_VISUAL_E2E === 'true') {
      i18n.options.fallbackLng = [];
    }
    this.cairoSessionId = (0, _uuid.v4)();
    this.biLogger = params.biLogger ?? (biLoggerFactory == null ? void 0 : biLoggerFactory().logger());
    this.i18n = i18n;
    this.internalMonitor = new _services.WixPatternsMonitor({
      errorMonitor: params.errorMonitor,
      internalErrorMonitor,
      internalFedops,
      environment: this.environment,
      csid: this.cairoSessionId
    });
    this.internalExperiments = internalExperiments;
    this.enableTranslatedKeySuffix = this.experiments.enabled('specs.cairo.example-bm.tagsToLabels') || this.experiments.enabled('specs.cairo.contacts.tagsToLabels');
    this.translate = (key, params) => {
      void this.initTask.status; // status is observable so reading it here starts mobx reactivity
      if (this.enableTranslatedKeySuffix) {
        return this.i18n.t(`${key}.asLabels`, {
          ...params,
          defaultValue: this.i18n.t(key, params)
        });
      }
      return this.i18n.t(key, params);
    };
    this.Trans = params.Trans;
    this.onlineState = new _OnlineState.OnlineState({
      onlineManager: this.onlineManager,
      focusManager: this.focusManager,
      translate: this.translate,
      showToast: this.showToast
    });
    this.reportBi = this.createBILogger({});
    (0, _mobx.makeObservable)(this, {
      init: _mobx.action.bound,
      initialFetch: _mobx.action.bound,
      dateFormatters: _mobx.computed,
      isPanelLayout: _mobx.computed
    });
  }
  setIsAutoPatterns(value) {
    this._isAutoPatterns = value;
  }
  _createComponentSettings(options) {
    return this.createComponentSettings(this)(options);
  }
  async initialFetch() {
    const {
      initTask,
      i18n,
      internalExperiments,
      experiments
    } = this;
    initTask.runOnce(async () => {
      await Promise.all([i18n.init(), internalExperiments == null ? void 0 : internalExperiments.ready().catch(e => {
        console.error(e);
      }), experiments.ready().catch(e => {
        console.error(e);
      }), this._messagesEnImport() // not all translation files contain all the keys, so en is required otherwise show error state
      ]);
    });
    return initTask.status.promise;
  }
  get dateFormatters() {
    return {
      medium: new Intl.DateTimeFormat(this.environment.language, {
        dateStyle: 'medium'
      }),
      mediumTime: new Intl.DateTimeFormat(this.environment.language, {
        dateStyle: 'medium',
        timeStyle: 'short'
      }),
      time: new Intl.DateTimeFormat(this.environment.language, {
        timeStyle: 'short'
      })
    };
  }
  get isPanelLayout() {
    return this.layoutType === 'panel';
  }
  get useRelativeSidePanel() {
    var _this$internalExperim;
    return this._useRelativeSidePanel || ((_this$internalExperim = this.internalExperiments) == null ? void 0 : _this$internalExperim.enabled('specs.cairo.useRelativeSidePanel'));
  }
  init() {
    const {
      onlineState
    } = this;
    this.initialFetch().catch(e => {
      console.error(e);
    });
    const disposers = [onlineState.init(), new _BeforeUnloadCompatState.BeforeUnloadCompatState(this).init()];
    return () => {
      disposers.forEach(d => d == null ? void 0 : d());
    };
  }
}
exports.WixPatternsContainer = WixPatternsContainer;
//# sourceMappingURL=WixPatternsContainer.js.map