import { addEventListener, WixPatternsError, DataExtensionState, TaskState, withoutDefaults, dateRangeFilter, idNameArrayFilter, numberRangeFilter, stringOperatorFilter, STRING_OPERATORS, } from '@wix/bex-core';
import { cairoErrorInLoadingAComponent, cairoTryAgainClicked, } from '@wix/bex-core/bi';
import { buildCustomFieldFilterElement } from '../CustomFieldFilters';
import { CollectionToolbarFilters, } from '../CollectionToolbarFilters';
import { reaction } from 'mobx';
import { CustomFieldsPanelState } from '../../state/CustomFields/CustomFieldsPanelState';
export class CollectionDataExtensionState {
    get featuredPageActions() {
        return [this.DataExtension.manageCustomFieldsPageAction];
    }
    constructor(params) {
        this.initTask = new TaskState();
        this.toolbar = params.toolbar;
        this.props = params.props;
        this.DataExtension = params.DataExtension;
        this.dataExtension = new DataExtensionState({
            container: params.container,
            fqdn: params.toolbar.collection.fqdn ?? {
                product: params.toolbar.collection.queryName,
            },
            closeSidePanel: params.toolbar.closeSidePanel,
            disableUserDefinedWriting: params.disableUserDefinedWriting,
            filterable: params.filterable,
            containsPii: params.containsPii,
            defaultPermissions: params.defaultPermissions,
            enableArchive: params.enableArchive,
        });
        this.customFieldsPanel = new CustomFieldsPanelState({
            dataExtension: this.dataExtension,
            reportBi: this.toolbar.reportBi,
            closeSidePanel: this.toolbar.closeSidePanel,
        });
        this.components = {
            CollectionToolbarFilters,
        };
    }
    _getFetchSchemasError(err) {
        return new WixPatternsError({
            errorCode: 'InitCustomFieldsDataExtensionFailed',
            originalException: err,
        });
    }
    _handleFetchSchemasError() {
        const error = this.dataExtension.initTask.status.error;
        if (!error) {
            return;
        }
        const cairoError = this._getFetchSchemasError(error);
        this.dataExtension.container.showToast?.({
            message: this.dataExtension.container.translate('cairo.customFields.fetch.technicalError'),
            action: {
                uiType: 'LINK',
                text: this.dataExtension.container.translate('cairo.toast.retry'),
                onClick: () => {
                    this.toolbar.reportBi(withoutDefaults(cairoTryAgainClicked)({
                        actionName: 'Fetch extended fields',
                        loaction: 'toast',
                    }));
                    this.dataExtension
                        .fetchSchemas()
                        .catch(this._handleFetchSchemasError.bind(this));
                },
                removeToastOnClick: true,
            },
            type: 'WARNING',
            biName: 'cairo-fetch-schemas-error-toast',
        });
        this.dataExtension.container.internalMonitor.reportError({
            error: cairoError,
        });
        this.toolbar.reportBi(cairoErrorInLoadingAComponent({
            errorType: cairoError.name,
        }));
    }
    _addCustomFieldFilters() {
        const createStringFilter = (params) => stringOperatorFilter({
            ...params,
            allowedOperators: STRING_OPERATORS,
        });
        const customFieldFilter = {
            date: dateRangeFilter,
            dateTime: dateRangeFilter,
            checkbox: idNameArrayFilter,
            decimal: numberRangeFilter,
            integer: numberRangeFilter,
            shortText: createStringFilter,
            url: createStringFilter,
            longText: createStringFilter,
        };
        this.dataExtension.filterableCustomFields.forEach((customField) => {
            const filter = customFieldFilter[customField.type];
            if (!filter) {
                return;
            }
            this.toolbar.collection.query.addFilterIfNeeded(customField.id, filter({
                name: customField.id,
                isCustomField: true,
            }));
        });
    }
    init() {
        const { initTask, dataExtension, toolbar } = this;
        const { customColumnsState } = toolbar;
        const disposers = [
            dataExtension.init(),
            reaction(() => this.dataExtension.filterableCustomFields, () => this._addCustomFieldFilters()),
            ...(customColumnsState?.events
                ? [
                    addEventListener(customColumnsState.events, 'beforeInitialFetch', () => initTask.status.promise),
                ]
                : []),
        ];
        initTask.runOnce(async () => {
            dataExtension.initTask.runOnce();
            dataExtension.container.initTask.runOnce();
            await Promise.all([
                dataExtension.initTask.status.promise?.catch(() => { }),
                dataExtension.container.initTask.status.promise,
            ]);
            this._handleFetchSchemasError();
            // Add custom field filters BEFORE initTask completes so collection waits for them
            this._addCustomFieldFilters();
            toolbar.setNewExtendedColumns(dataExtension.availableCustomFields, {
                defaultHidden: true,
            });
        });
        return () => {
            disposers.forEach((d) => d?.());
        };
    }
    buildCustomFieldFilterWrapper(customField) {
        return (buildCustomFieldFilterElement(this.toolbar, customField) ||
            undefined);
    }
    buildCustomFieldFilters() {
        return this.dataExtension.filterableCustomFields
            .map((customField) => this.buildCustomFieldFilterWrapper(customField))
            .filter(Boolean);
    }
}
//# sourceMappingURL=CollectionDataExtensionState.js.map