"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.ExportState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _http = require("@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/http");
var _types = require("@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/types");
var _mobx = require("mobx");
var _model = require("../../model");
var _services = require("../../services");
var _mapValues = _interopRequireDefault(require("lodash/mapValues"));
var _events = require("events");
var _ExportStateBIReporter = require("./ExportStateBIReporter");
var _getJobItemsAbsoluteCounter = require("../getJobItemsAbsoluteCounter");
var _getExportAsyncJobErrors = require("./getExportAsyncJobErrors");
var _createExportAsyncJobErrors = require("./createExportAsyncJobErrors");
var _commonExportAsyncJobErrors = require("./commonExportAsyncJobErrors");
function defaultPlatformizedQuery() {
  return {
    filter: {},
    sort: []
  };
}
class ExportState {
  constructor(props) {
    (0, _defineProperty2.default)(this, "exportStatus", {
      ..._model.queryStatus.idle
    });
    (0, _defineProperty2.default)(this, "config", {
      pollingDelay: 2000,
      stateJob: {
        maxPolling: 14,
        maxRetries: 1
      },
      queryJobRetries: {
        delay: 5000,
        max: 4
      }
    });
    (0, _defineProperty2.default)(this, "exportStartTime", 0);
    (0, _defineProperty2.default)(this, "totalForExport", null);
    (0, _defineProperty2.default)(this, "selectedExportOption", 'all');
    (0, _defineProperty2.default)(this, "disabledRadios", void 0);
    (0, _defineProperty2.default)(this, "maybeToast", void 0);
    (0, _defineProperty2.default)(this, "iterationsCountPoll", {
      iterationsCount: 0,
      pollCount: 0,
      retries: 0
    });
    (0, _defineProperty2.default)(this, "queryJobRetries", {
      count: 0
    });
    (0, _defineProperty2.default)(this, "differentQueryEndpointThanCollection", void 0);
    (0, _defineProperty2.default)(this, "customTotal", void 0);
    (0, _defineProperty2.default)(this, "translate", void 0);
    (0, _defineProperty2.default)(this, "createExportAsyncJobRequest", void 0);
    (0, _defineProperty2.default)(this, "saveAs", void 0);
    (0, _defineProperty2.default)(this, "window", void 0);
    (0, _defineProperty2.default)(this, "httpClient", void 0);
    (0, _defineProperty2.default)(this, "errorHandler", void 0);
    (0, _defineProperty2.default)(this, "onlineState", void 0);
    (0, _defineProperty2.default)(this, "exportModalState", void 0);
    (0, _defineProperty2.default)(this, "collectionPageState", void 0);
    (0, _defineProperty2.default)(this, "transformPlatformizedQuery", void 0);
    (0, _defineProperty2.default)(this, "showToast", void 0);
    (0, _defineProperty2.default)(this, "internalMonitor", void 0);
    (0, _defineProperty2.default)(this, "collection", void 0);
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "bi", void 0);
    (0, _defineProperty2.default)(this, "events", new _events.EventEmitter());
    (0, _defineProperty2.default)(this, "counter", 0);
    (0, _defineProperty2.default)(this, "absoluteCounter", 0);
    (0, _defineProperty2.default)(this, "retries", 0);
    (0, _defineProperty2.default)(this, "currentStep", 'config');
    (0, _defineProperty2.default)(this, "totalForExportGettersMap", {
      selected: (0, _mobx.action)(() => {
        const {
          collection
        } = this;
        const {
          bulkSelect: {
            selectedCountOrTotal
          }
        } = collection;
        return selectedCountOrTotal;
      }),
      filtered: (0, _mobx.action)(() => {
        const {
          collection
        } = this;
        const {
          result: {
            total,
            supportTotal
          }
        } = collection;
        if (!supportTotal) {
          return null;
        }
        return total;
      }),
      all: (0, _mobx.action)(async () => {
        const {
          collection
        } = this;
        const allItemsQuery = {
          ...collection.query.asComputed,
          filtersKey: (0, _mapValues.default)(collection.query.customFilters, filter => filter != null ? null : undefined),
          rawFilters: {},
          filters: {}
        };
        const queryKey = collection._queryKey(allItemsQuery);
        const allItemsQueryResult = await collection.queryClient.fetchQuery({
          queryFn: () => collection._queryFn(allItemsQuery),
          queryKey
        });
        return allItemsQueryResult.total;
      })
    });
    (0, _defineProperty2.default)(this, "beforeunload", e => {
      e.preventDefault();
      e.returnValue = '';
    });
    this.customTotal = props.customTotal;
    this.differentQueryEndpointThanCollection = props.differentQueryEndpointThanCollection;
    this.translate = props.translate;
    this.createExportAsyncJobRequest = props.createExportAsyncJobRequest;
    this.saveAs = props.saveAs;
    this.window = props.window;
    this.httpClient = props.httpClient;
    this.errorHandler = props.errorHandler;
    this.onlineState = props.onlineState;
    this.exportModalState = props.exportModalState;
    this.collectionPageState = props.collectionPageState;
    this.showToast = props.showToast;
    this.internalMonitor = props.internalMonitor;
    this.collection = props.collection;
    this.reportBi = props.reportBi;
    this.disabledRadios = [];
    this.transformPlatformizedQuery = props.transformPlatformizedQuery;
    this.bi = new _ExportStateBIReporter.ExportStateBIReporter(this);
    (0, _mobx.makeObservable)(this, {
      exportStatus: _mobx.observable.ref,
      iterationsCountPoll: _mobx.observable.ref,
      isExporting: _mobx.computed,
      totalForExport: _mobx.observable.ref,
      selectedExportOption: _mobx.observable.ref,
      disabledRadios: _mobx.observable.ref,
      counter: _mobx.observable.ref,
      absoluteCounter: _mobx.observable.ref,
      onExportToClick: _mobx.action.bound,
      onExportCloseAttemptClick: _mobx.action.bound,
      onCancelExportCloseButtonClick: _mobx.action.bound,
      onCancelExportGoBackButtonClick: _mobx.action.bound,
      onExportSecondaryActionAttempt: _mobx.action.bound,
      onRetryExportToClick: _mobx.action.bound,
      onFailedClose: _mobx.action.bound,
      onFailedCancel: _mobx.action.bound,
      onCancelClick: _mobx.action.bound,
      onCloseClick: _mobx.action.bound,
      init: _mobx.action.bound,
      setTotalForExport: _mobx.action,
      onExportTypeChange: _mobx.action,
      hasFilters: _mobx.computed,
      totalForExportMap: _mobx.computed,
      hasSelectedRows: _mobx.computed,
      isAllSelected: _mobx.computed,
      currentStep: _mobx.observable.ref,
      _onJobSuccess: _mobx.action,
      _checkIfStaleJob: _mobx.action,
      _throwJobError: _mobx.action,
      _updateJobProgress: _mobx.action
    });
  }
  get isModalOpen() {
    return this.exportModalState.isOpen;
  }
  get isExporting() {
    const {
      exportStatus
    } = this;
    return exportStatus.isLoading || exportStatus.isSuccess;
  }
  _cancelJob() {
    // const { events } = this;
    // events.once('afterJobCreated', ({ job }) => {
    //   const { httpClient } = this;
    //   httpClient.request(
    //     cancelExportAsyncJob({
    //       jobId: job.id as string,
    //     }),
    //   );
    // });
  }
  _reset() {
    this.exportStatus = {
      ..._model.queryStatus.idle
    };
    this.currentStep = 'config';
    this.counter = 0;
    this.absoluteCounter = 0;
    this.totalForExport = null;
  }
  onExportTypeChange(selectedExportOption) {
    this.bi.onExportTypeChange({
      prev: this.selectedExportOption,
      next: selectedExportOption
    });
    this.selectedExportOption = selectedExportOption;
  }
  init() {
    var _this$maybeToast;
    const {
      onlineState
    } = this;
    (_this$maybeToast = this.maybeToast) == null || _this$maybeToast.remove();
    if (this.hasSelectedRows) {
      this.disabledRadios = this.hasFilters ? [] : ['filtered'];
      this.selectedExportOption = 'selected';
    } else if (this.hasFilters) {
      this.disabledRadios = ['selected'];
      this.selectedExportOption = 'filtered';
    } else {
      this.disabledRadios = ['selected', 'filtered'];
      this.selectedExportOption = 'all';
    }
    this.bi.clickOpenModal();
    const onOnlineChanged = (0, _mobx.action)(isOnline => {
      if (isOnline && this.currentStep === 'error') {
        this.currentStep = 'progress';
        this.events.emit('online');
      }
    });
    onlineState.events.on('change', onOnlineChanged);
    return () => {
      window.removeEventListener('beforeunload', this.beforeunload);
      this.events.removeAllListeners('undoCancel');
      this.events.removeAllListeners('online');
      onlineState.events.off('change', onOnlineChanged);
    };
  }
  get hasFilters() {
    return this.collection.query.hasActiveFilters;
  }
  get hasSelectedRows() {
    return this.collection.bulkSelect.selectedIds.length !== undefined && this.collection.bulkSelect.selectedIds.length > 0;
  }
  get isAllSelected() {
    return this.collection.bulkSelect.allSelected;
  }
  get totalForExportMap() {
    return {
      selected: this.totalForExportGettersMap.selected(),
      filtered: this.totalForExportGettersMap.filtered()
    };
  }
  async setTotalForExport(params) {
    const {
      selectedExportOption,
      collection
    } = this;
    const {
      result: {
        supportTotal
      }
    } = collection;
    if (this.differentQueryEndpointThanCollection === true) {
      return;
    }
    const collectionTotalPromise = (() => {
      if (selectedExportOption === 'selected') {
        return this.totalForExportGettersMap.selected();
      }
      if (selectedExportOption === 'filtered' && supportTotal) {
        return this.totalForExportGettersMap.filtered();
      }
      return this.totalForExportGettersMap.all();
    })();
    if (this.customTotal) {
      const totalForExport = await this.customTotal({
        ...params,
        collectionTotalPromise
      });
      (0, _mobx.runInAction)(() => {
        this.totalForExport = totalForExport;
      });
      return;
    }
    const totalForExport = await collectionTotalPromise;
    (0, _mobx.runInAction)(() => {
      this.totalForExport = totalForExport;
    });
  }
  onCancelClick() {
    const {
      bi,
      exportModalState
    } = this;
    bi.onCancelClick();
    exportModalState.close();
  }
  onCancelExportVerifyButtonClick() {
    const {
      bi,
      exportModalState
    } = this;
    bi.onCancelExportButtonClick();
    exportModalState.close();
  }
  onCancelExportGoBackButtonClick() {
    this.currentStep = 'progress';
    const {
      bi,
      events
    } = this;
    bi.onCancelExportGoBackButtonClick();
    events.emit('undoCancel');
  }
  onCancelExportCloseButtonClick() {
    this.currentStep = 'progress';
    const {
      bi,
      events
    } = this;
    bi.onCancelExportCloseButtonClick();
    events.emit('undoCancel');
  }
  onExportCloseAttemptClick() {
    this.currentStep = 'cancel';
    const {
      bi
    } = this;
    bi.onExportCloseAttemptClick();
  }
  onExportSecondaryActionAttempt() {
    this.currentStep = 'cancel';
    const {
      bi
    } = this;
    bi.onExportCancelAttemptClick();
  }
  onCloseClick() {
    const {
      bi,
      exportModalState
    } = this;
    bi.onCloseClick();
    exportModalState.close();
  }
  async onExportToClick() {
    const {
      internalMonitor,
      bi
    } = this;
    this.retries += 1;
    this.iterationsCountPoll = {
      iterationsCount: 0,
      retries: 0,
      pollCount: 0
    };
    this.queryJobRetries = {
      count: 0
    };
    this.exportStartTime = performance.now();
    internalMonitor.interactionStarted('export-to');
    bi.onExportToClick();
    const reportExportEnd = bi.onExportStart();
    this._exportTo({
      onExportEnd: (0, _mobx.action)(params => {
        if (params.result !== 'fail') {
          internalMonitor.interactionEnded('export-to');
        }
        reportExportEnd(params);
      })
    });
  }
  async onRetryExportToClick() {
    const {
      bi
    } = this;
    bi.onRetryExportToClick();
    await this.onExportToClick();
  }
  async onFailedClose() {
    const {
      bi,
      exportModalState
    } = this;
    bi.onFailedClose();
    exportModalState.close();
  }
  async onFailedCancel() {
    const {
      bi,
      exportModalState
    } = this;
    bi.onFailedCancel();
    exportModalState.close();
  }
  async _onJobSuccess(job, params) {
    var _job$data, _this$showToast;
    const {
      events,
      exportModalState,
      translate: t
    } = this;
    const {
      onExportEnd,
      query,
      saveAs
    } = params;
    if (((_job$data = job.data) == null ? void 0 : _job$data.signedUrl) == null) {
      return;
    }
    if (this.currentStep === 'cancel') {
      events.once('undoCancel', async () => {
        await new Promise(resolve => setTimeout(resolve, 1000));
        return this._onJobSuccess(job, {
          onExportEnd,
          query,
          saveAs
        });
      });
      return;
    }
    (0, _mobx.runInAction)(() => {
      this.exportStatus = {
        ..._model.queryStatus.success,
        data: job
      };
      this.counter = 100;
      this._updateAbsoluteCounter(job, params);
    });
    window.removeEventListener('beforeunload', this.beforeunload);
    await new Promise(res => setTimeout(res, 1000)); // wait bit before starting the download for the progress indication animation completes

    const signedUrl = job.data.signedUrl;
    onExportEnd({
      job,
      query,
      result: 'success',
      saveAs
    });
    const biState = this.bi.beforeToast();
    const maybeToast = (_this$showToast = this.showToast) == null ? void 0 : _this$showToast.call(this, {
      message: t('cairo.export.successMessage'),
      biName: 'cairo-export-success-toast',
      timeout: 'NONE',
      type: 'SUCCESS',
      onCloseClick: () => {
        this.bi.onToastDismissed({
          ...biState,
          by: 'manual'
        });
        this.maybeToast = undefined;
      },
      action: {
        text: t('cairo.export.downloadManually'),
        uiType: 'LINK',
        navigationTarget: {
          url: signedUrl,
          openInNewTab: true
        },
        onClick: () => {
          this.bi.onToastActionClick(biState);
          this.maybeToast = undefined;
        }
      }
    });
    this.maybeToast = maybeToast;
    this.window.download(signedUrl, saveAs);
    if (maybeToast) {
      new Promise(resolve => setTimeout(resolve, 6000)).then(() => {
        if (maybeToast === this.maybeToast) {
          maybeToast.remove();
          this.bi.onToastDismissed({
            ...biState,
            by: 'automatic'
          });
        }
      });
    }
    exportModalState.close();
  }
  _throwJobError(job, {
    onExportEnd,
    query
  }) {
    var _job$data2, _job$data3, _job$data4;
    if (((_job$data2 = job.data) == null || (_job$data2 = _job$data2.error) == null || (_job$data2 = _job$data2.applicationError) == null ? void 0 : _job$data2.code) === 'job_cancelled_by_client') {
      onExportEnd({
        job,
        query,
        result: 'stopped by user'
      });
      return;
    }
    onExportEnd({
      job,
      query,
      result: 'fail'
    });
    throw Object.assign(new Error(`ExportAsyncJob.${(_job$data3 = job.data) == null || (_job$data3 = _job$data3.error) == null || (_job$data3 = _job$data3.applicationError) == null ? void 0 : _job$data3.code}`), {
      response: {
        data: (_job$data4 = job.data) == null ? void 0 : _job$data4.error
      },
      job,
      query
    });
  }
  _checkIfStaleJob(job, {
    onExportEnd,
    query
  }) {
    var _job$data5, _job$data6;
    const {
      internalMonitor
    } = this;
    if (job.status === _types.Status.FINISHED && !((_job$data5 = job.data) != null && _job$data5.signedUrl)) {
      internalMonitor.interactionStarted('export-to-finished-without-download-url');
      internalMonitor.interactionEnded('export-to-finished-without-download-url');
    }
    if (((_job$data6 = job.data) == null ? void 0 : _job$data6.iterationsCount) === this.iterationsCountPoll.iterationsCount) {
      var _job$data7;
      this.iterationsCountPoll = {
        ...this.iterationsCountPoll,
        pollCount: this.iterationsCountPoll.pollCount + 1
      };
      if (((_job$data7 = job.data) == null ? void 0 : _job$data7.completionStep) !== 'upload' && this.iterationsCountPoll.pollCount > this.config.stateJob.maxPolling) {
        if (this.iterationsCountPoll.retries < this.config.stateJob.maxRetries) {
          internalMonitor.interactionStarted('export-to-max-polling-stale-job');
          internalMonitor.interactionEnded('export-to-max-polling-stale-job');
          (0, _mobx.runInAction)(() => {
            this.iterationsCountPoll = {
              iterationsCount: 0,
              pollCount: 0,
              retries: this.iterationsCountPoll.retries + 1
            };
          });
          window.removeEventListener('beforeunload', this.beforeunload);
          this._exportTo({
            onExportEnd
          });
          return 'restarted';
        }
        onExportEnd({
          job,
          query,
          result: 'fail'
        });
        throw Object.assign(new Error('ExportAsyncJob.max_polling_stale_job'), {
          response: {
            data: {
              applicationError: {
                code: 'max_polling_stale_job'
              }
            }
          }
        });
      }
    } else {
      var _job$data8;
      this.iterationsCountPoll = {
        ...this.iterationsCountPoll,
        iterationsCount: (_job$data8 = job.data) == null ? void 0 : _job$data8.iterationsCount,
        pollCount: 1
      };
    }
    return;
  }
  _updateAbsoluteCounter(job, {
    query
  }) {
    if ((job == null ? void 0 : job.data) == null) {
      return;
    }
    const {
      totalForExport
    } = this;
    const newAbsoluteCounter = (0, _getJobItemsAbsoluteCounter.getJobItemsAbsoluteCounter)(job, {
      query,
      totalForExport
    });
    this.absoluteCounter = totalForExport != null && newAbsoluteCounter >= totalForExport && !this.exportStatus.isSuccess ? this.absoluteCounter + Math.floor(Math.random() * (newAbsoluteCounter - this.absoluteCounter)) : newAbsoluteCounter;
  }
  _updateJobProgress(job, params) {
    this._updateAbsoluteCounter(job, params);
    const {
      totalForExport
    } = this;
    if (totalForExport) {
      if (this.absoluteCounter) {
        const newCounter = Math.round(this.absoluteCounter / totalForExport * 100);
        this.counter = newCounter === 100 ? this.counter + Math.round(Math.random() * (99 - this.counter)) : newCounter;
      }
    } else if (this.counter < 90 && this.absoluteCounter > 0) {
      this.counter += 10;
    }
  }
  async _poll({
    jobId,
    saveAs,
    query,
    onExportEnd
  }) {
    const {
      httpClient,
      events,
      onlineState,
      translate,
      errorHandler
    } = this;
    let current = null;
    try {
      // eslint-disable-next-line no-constant-condition
      while (true) {
        var _job$data$error;
        if (!this.isModalOpen) {
          const currentJob = await this.exportStatus.promise;
          if (currentJob) {
            onExportEnd({
              job: currentJob,
              query,
              result: 'stopped by user'
            });
          }
          break;
        }
        const getExportAsyncJobResponse = await errorHandler.withErrorHandler(() => httpClient.request((0, _http.getExportAsyncJob)({
          jobId
        })), (0, _getExportAsyncJobErrors.getExportAsyncJobErrors)({
          translate,
          retryFn: this.onRetryExportToClick
        }), {
          statusCodesOverrides: (0, _commonExportAsyncJobErrors.commonExportAsyncJobErrors)({
            translate
          })
        }).catch(error => {
          errorHandler.getResolvedError == null || errorHandler.getResolvedError(error);
          return {
            error
          };
        });
        if (getExportAsyncJobResponse && !('data' in getExportAsyncJobResponse)) {
          const error = getExportAsyncJobResponse.error;
          if (!onlineState.isOnline) {
            events.once('online', () => {
              this._poll({
                jobId,
                onExportEnd,
                query,
                saveAs
              });
            });
            throw new _services.WixPatternsError({
              errorCode: 'GetExportAsyncJob.offline',
              originalException: error,
              extraData: {
                response: {
                  data: {
                    applicationError: {
                      code: 'offline'
                    }
                  }
                }
              }
            });
          }
          if (this.queryJobRetries.count > this.config.queryJobRetries.max) {
            onExportEnd({
              job: current,
              query,
              result: 'fail'
            });
            throw new _services.WixPatternsError({
              originalException: error,
              errorCode: 'GetExportAsyncJob.failed'
            });
          }
          this.queryJobRetries = {
            ...this.queryJobRetries,
            count: this.queryJobRetries.count + 1
          };
          setTimeout(() => {
            this._poll({
              jobId,
              onExportEnd,
              query,
              saveAs
            });
          }, this.config.queryJobRetries.delay);
          break;
        }
        const job = getExportAsyncJobResponse == null ? void 0 : getExportAsyncJobResponse.data.job;
        if ((job == null ? void 0 : job.data) == null) {
          throw new _services.WixPatternsError({
            errorCode: 'GetExportAsyncJob.invalid'
          });
        }
        current = job;
        this.queryJobRetries = {
          count: 0
        };
        (0, _mobx.runInAction)(() => {
          this.exportStatus = {
            ..._model.queryStatus.loading,
            promise: Promise.resolve(job)
          };
        });
        const isModalOpen = (0, _mobx.runInAction)(() => this.isModalOpen);
        if (!isModalOpen) {
          break;
        }
        if (job.data.signedUrl) {
          await this._onJobSuccess(job, {
            onExportEnd,
            saveAs,
            query
          });
          break;
        }
        if (job.status === _types.Status.FAILED || ((_job$data$error = job.data.error) == null ? void 0 : _job$data$error.applicationError) != null) {
          var _job$data$error2;
          if (((_job$data$error2 = job.data.error) == null || (_job$data$error2 = _job$data$error2.applicationError) == null ? void 0 : _job$data$error2.code) === 'media_generate_signed_url') {
            // await this._retryGenerateUrl(job);
            // continue;
          }
          this._throwJobError(job, {
            onExportEnd,
            query,
            saveAs
          });
          break;
        }
        const checkIfStaleJobResult = this._checkIfStaleJob(job, {
          onExportEnd,
          saveAs,
          query
        });
        if (checkIfStaleJobResult === 'restarted') {
          return;
        }
        await (0, _mobx.runInAction)(async () => {
          var _job$data9;
          if (!this.totalForExport && (((_job$data9 = job.data) == null ? void 0 : _job$data9.iterationsCount) == null || job.data.iterationsCount <= 1)) {
            var _job$data0;
            this.totalForExport = (_job$data0 = job.data) == null || (_job$data0 = _job$data0.pagingMetadata) == null ? void 0 : _job$data0.total;
          }
        });
        this._updateJobProgress(job, {
          onExportEnd,
          query,
          saveAs
        });
        await new Promise(res => setTimeout(res, this.config.pollingDelay));
      }
    } catch (error) {
      console.error(error);
      this.internalMonitor.reportError({
        error
      });
      (0, _mobx.runInAction)(() => {
        this.currentStep = 'error';
        this.exportStatus = {
          ..._model.queryStatus.error,
          error
        };
      });
    }
  }
  async _exportTo({
    onExportEnd
  }) {
    var _this$saveAs;
    const {
      createExportAsyncJobRequest,
      httpClient,
      errorHandler,
      transformPlatformizedQuery,
      selectedExportOption,
      events,
      onlineState,
      translate
    } = this;
    this._reset();
    window.addEventListener('beforeunload', this.beforeunload);
    const platformizedQuery = defaultPlatformizedQuery();
    const {
      bulkSelect: {
        selectedIds,
        allSelected: selectAll,
        uncheckedInCurrentCollection: uncheckedValues
      },
      query: {
        asComputed: computedQuery
      }
    } = this.collection;
    const wixPatternsQuery = selectedExportOption !== 'all' ? computedQuery : {
      ...computedQuery,
      filtersKey: {},
      rawFilters: {},
      filters: {}
    };
    const exportPublicState = {
      platformizedQuery,
      wixPatternsQuery,
      selectedItems: selectedExportOption === 'selected' ? selectedIds : undefined,
      isSelectAll: selectAll,
      uncheckedValues
    };
    const query = (await (transformPlatformizedQuery == null ? void 0 : transformPlatformizedQuery(exportPublicState))) ?? platformizedQuery;
    const totalForExportPromise = this.setTotalForExport({
      ...exportPublicState,
      platformizedQuery: query
    });
    const saveAs = ((_this$saveAs = this.saveAs) == null ? void 0 : _this$saveAs.call(this, {
      platformizedQuery,
      wixPatternsQuery,
      selectedItems: selectedExportOption === 'selected' ? selectedIds : undefined,
      isSelectAll: selectAll
    })) ?? this.collectionPageState.pageTitle;
    (0, _mobx.runInAction)(() => {
      this.currentStep = 'progress';
    });
    const _createExport = async () => {
      try {
        const {
          data: createExportAsyncJobResponse
        } = await errorHandler.withErrorHandler(() => httpClient.request((0, _http.createExportAsyncJob)({
          fields: [],
          methodMetadata: {},
          ...createExportAsyncJobRequest,
          saveAs,
          query
        })), (0, _createExportAsyncJobErrors.createExportAsyncJobErrors)({
          translate
        }), {
          statusCodesOverrides: (0, _commonExportAsyncJobErrors.commonExportAsyncJobErrors)({
            translate
          })
        }).catch(err => {
          if (!onlineState.isOnline) {
            events.once('online', () => {
              this._exportTo({
                onExportEnd
              });
            });
            throw Object.assign(new Error('CreateExportAsyncJob.offline'), {
              response: {
                data: {
                  applicationError: {
                    code: 'offline'
                  }
                }
              }
            });
          }
          onExportEnd({
            job: null,
            query,
            result: 'fail'
          });
          throw err;
        });
        return createExportAsyncJobResponse;
      } catch (error) {
        (0, _mobx.runInAction)(() => {
          this.currentStep = 'error';
          this.exportStatus = {
            ..._model.queryStatus.error,
            error
          };
        });
        throw error;
      }
    };
    try {
      var _createExportAsyncJob;
      const createExportAsyncJobResponse = await _createExport();
      if (!((_createExportAsyncJob = createExportAsyncJobResponse.job) != null && _createExportAsyncJob.id)) {
        var _createExportAsyncJob2;
        throw new Error(`Invalid response from createExportAsyncJob "jobId=${(_createExportAsyncJob2 = createExportAsyncJobResponse.job) == null ? void 0 : _createExportAsyncJob2.id}"`);
      }
      await totalForExportPromise;
      (0, _mobx.runInAction)(() => {
        this.exportStatus = {
          ..._model.queryStatus.loading,
          promise: Promise.resolve(createExportAsyncJobResponse.job)
        };
      });
      this.events.emit('afterJobCreated', {
        job: createExportAsyncJobResponse.job
      });
      (0, _mobx.runInAction)(() => {
        this.counter = 1;
      });
      await this._poll({
        onExportEnd,
        saveAs,
        query,
        jobId: createExportAsyncJobResponse.job.id
      });
    } catch (error) {
      console.error(error);
      this.internalMonitor.reportError({
        error
      });
    }
    window.removeEventListener('beforeunload', this.beforeunload);
  }
}
exports.ExportState = ExportState;
//# sourceMappingURL=ExportState.js.map