import { fetchTranslations, messagesEnImportGlobal, WixPatternsMonitor, } from '../services';
import { wixPatternsEnvironment, } from '../model';
import { action, computed, makeObservable } from 'mobx';
import { TaskState } from './TaskState';
import { OnlineState } from './OnlineState';
import { createComponentSettings } from '../services/createComponentSettings';
import { ConditionalModalState } from './ConditionalModalState';
import { EventEmitter } from 'events';
import { fixDomainForBI } from '../util';
import { createUseExperimentsCompat } from './useExperimentsCompat';
import { v4 as uuid } from 'uuid';
import { BeforeUnloadCompatState } from './BeforeUnloadCompatState';
export class WixPatternsContainer {
    constructor(params) {
        this.initTask = new TaskState();
        this._isAutoPatterns = false;
        this.createBILogger = (defaultParams) => {
            return (reportProps) => {
                const { environment, environmentBI, cairoSessionId, biLogger, user } = this;
                const { params: { url, ...rest }, } = reportProps;
                return 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: fixDomainForBI(url) }),
                        ...rest,
                    },
                });
            };
        };
        this.createEssentials = params.createEssentials;
        this.lodash = params.lodash;
        this.patchesCache = params.patchesCache;
        this.events =
            params.events ?? new EventEmitter();
        this._messagesEnImport = params.messagesEnImport ?? messagesEnImportGlobal;
        this._fetchTranslations = params.fetchTranslations ?? fetchTranslations;
        this.onNavigationModal =
            params.onNavigationModal ?? new ConditionalModalState();
        this.environment = wixPatternsEnvironment(params.environment);
        this.environmentBI = params.environmentBI;
        this.user = params.user;
        this.contextType = params.contextType ?? 'SITE';
        this.createComponentSettings =
            params.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: () => {
                const { translate: t } = this;
                this.showToast?.({
                    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 = 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?.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 = uuid();
        this.biLogger = params.biLogger ?? biLoggerFactory?.().logger();
        this.i18n = i18n;
        this.internalMonitor = new 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({
            onlineManager: this.onlineManager,
            focusManager: this.focusManager,
            translate: this.translate,
            showToast: this.showToast,
        });
        this.reportBi = this.createBILogger({});
        makeObservable(this, {
            init: action.bound,
            initialFetch: action.bound,
            dateFormatters: computed,
            isPanelLayout: 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?.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() {
        return (this._useRelativeSidePanel ||
            this.internalExperiments?.enabled('specs.cairo.useRelativeSidePanel'));
    }
    init() {
        const { onlineState } = this;
        this.initialFetch().catch((e) => {
            console.error(e);
        });
        const disposers = [
            onlineState.init(),
            new BeforeUnloadCompatState(this).init(),
        ];
        return () => {
            disposers.forEach((d) => d?.());
        };
    }
}
//# sourceMappingURL=WixPatternsContainer.js.map