"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.NestedTableFlatModeState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _bexCore = require("@wix/bex-core");
var _TableVirtualState = require("../TableVirtualState");
var _NestedTableFlatModeSectionState = require("./NestedTableFlatModeSectionState");
var _util = require("@wix/bex-core/util");
var _NestedTableFlatModeStateBIReporter = require("./NestedTableFlatModeStateBIReporter");
class NestedTableFlatModeState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "wrapper", void 0);
    (0, _defineProperty2.default)(this, "virtual", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _bexCore.TaskState());
    (0, _defineProperty2.default)(this, "refreshTask", new _bexCore.TaskState());
    (0, _defineProperty2.default)(this, "sections", void 0);
    (0, _defineProperty2.default)(this, "multi", void 0);
    (0, _defineProperty2.default)(this, "bi", void 0);
    (0, _defineProperty2.default)(this, "initSearchState", void 0);
    (0, _defineProperty2.default)(this, "retryErrorState", (0, _mobx.action)(() => {
      const {
        initTask,
        refreshTask
      } = this;
      if (initTask.status.isError) {
        initTask.runOnce();
      } else if (refreshTask.status.isError) {
        refreshTask.runOnce();
      } else {
        this.multi.retryErrorState();
      }
    }));
    (0, _defineProperty2.default)(this, "_runSearch", (0, _mobx.action)(async () => {
      const {
        query,
        refreshTask
      } = this;
      if (query.search.isEmpty) {
        return;
      }
      refreshTask.reset();
      refreshTask.runOnce(() => this._populateCacheAndSearch());
    }));
    (0, _defineProperty2.default)(this, "_refreshAll", (0, _mobx.action)(() => {
      this.sections.forEach(({
        collection
      }) => {
        collection.clearResultAndMoveToStart();
      });
    }));
    const {
      wrapper
    } = params;
    this.wrapper = wrapper;
    const {
      levels,
      query: _query
    } = wrapper;
    this.bi = new _NestedTableFlatModeStateBIReporter.NestedTableFlatModeStateBIReporter(this);
    this.sections = Array.from(levels.map(levelDescriptor => {
      return new _NestedTableFlatModeSectionState.NestedTableFlatModeSectionState({
        levelDescriptor,
        query: _query,
        flatModeState: this
      });
    }).reduce((map, section) => {
      const query = section.collection.getCurrentQuery();
      const existingSection = map.get(query);
      if (existingSection) {
        existingSection.levelDescriptors.push(section.levelDescriptor);
      } else {
        map.set(query, section);
        section.levelDescriptors.push(section.levelDescriptor);
      }
      return map;
    }, new Map()).values());
    this.multi = new _bexCore.MultiCollectionSupport({
      collections: this.sections.map(({
        collection
      }) => collection)
    });
    this.virtual = new _TableVirtualState.TableVirtualState({
      table: this
    });
    this.initSearchState = this._getSearchInitState();
    (0, _mobx.makeObservable)(this, {
      keyedItems: _mobx.computed
    });
  }
  get toolbar() {
    return this.wrapper.toolbar;
  }
  get tableState() {
    return this.wrapper.tableState;
  }
  get keyedItems() {
    return this.sections.reduce((acc, section) => {
      const {
        collection: {
          result: {
            keyedItems
          }
        }
      } = section;
      return [...acc, ...keyedItems.map(keyedItem => ({
        ...keyedItem,
        item: {
          state: section,
          originalKeyedItem: keyedItem
        }
      }))];
    }, []);
  }
  get showEmptyState() {
    return this.multi.showEmptyState;
  }
  get hasAvailableItems() {
    return this.multi.hasAvailableItems;
  }
  get resultOriginQuerySearch() {
    return this.multi.resultOriginQuerySearch;
  }
  get hasNonPersistentActiveFilters() {
    return this.multi.hasNonPersistentActiveFilters;
  }
  get showErrorState() {
    const {
      initTask,
      refreshTask,
      multi
    } = this;
    return initTask.status.isError || refreshTask.status.isError || multi.showErrorState;
  }
  get showLoadingState() {
    return this.initTask.status.isIdle || this.initTask.status.isLoading || this.refreshTask.status.isLoading || this.multi.showLoadingState;
  }
  get errorStatus() {
    const {
      initTask,
      refreshTask,
      multi
    } = this;
    return initTask.errorStatus || refreshTask.errorStatus || multi.errorStatus;
  }
  get query() {
    return this.wrapper.query;
  }
  get levels() {
    return this.wrapper.levels;
  }
  async _populateCacheAndSearch() {
    const {
      wrapper,
      bi
    } = this;
    const reportSearchResults = bi._createReportSearchResults();
    const fetchAll = wrapper._attemptFetchAllAndPopulateCache();
    fetchAll.init();
    await fetchAll.initTask.status.promise;
    await this.toolbar.collection._runSearch(true);
    await Promise.all(this.sections.map(({
      collection
    }) => collection._runSearch(true)));
    reportSearchResults();
  }
  _getSearchInitState() {
    const initTask = new _bexCore.TaskState();
    const disposers = [...this.sections.map(({
      collection
    }) => (0, _util.addEventListener)(collection.hooks, 'beforeInitialFetch', () => initTask.status.promise))];
    return {
      initTask,
      init: () => {
        initTask.runOnce(async () => {
          await this._populateCacheAndSearch();
        });
        return () => {
          disposers.forEach(d => d());
        };
      }
    };
  }
  init({
    isUsingCache = false
  } = {}) {
    const {
      initTask,
      wrapper,
      multi,
      sections,
      initSearchState
    } = this;
    const {
      query
    } = wrapper;
    const disposers = [wrapper.init(), initSearchState.init(), multi.init(), (0, _util.addEventListener)(query.search.events, 'change', this._runSearch), ...sections.map(section => section.init())];
    if (!isUsingCache && initTask.status.isSuccess) {
      this._runSearch();
    }
    initTask.runOnce(async () => {
      wrapper.initTask.runOnce();
      initSearchState.initTask.runOnce();
      multi.initTask.runOnce();
      await wrapper.initTask.status.promise;
      await initSearchState.initTask.status.promise;
      await multi.initTask.status.promise;
    });
    return () => {
      disposers.forEach(d => d());
    };
  }
}
exports.NestedTableFlatModeState = NestedTableFlatModeState;
//# sourceMappingURL=NestedTableFlatModeState.js.map