import { DateUtils, UserInterface } from '@sankhyalabs/core';
import { default as InMemoryFilterColumnDataSource } from '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource';
import PreloadManager from '../../../lib/http/data-fetcher/fetchers/data-unit/cache/PreloadManager';
export default class SnkMultiSelectionListDataSource {
  setDataUnit(dataUnit) {
    this._dataUnit = dataUnit;
  }
  setApplication(application) {
    this._application = application;
  }
  formatLabel(fieldName, value) {
    const { userInterface } = this._dataUnit.getField(fieldName);
    if (userInterface === UserInterface.DATETIME) {
      return DateUtils.formatDate(this._dataUnit.valueFromString(fieldName, value));
    }
    return String(this._dataUnit.getFormattedValue(fieldName, value));
  }
  async getStaticOptions(fieldName, options) {
    if (fieldName == undefined) {
      return Promise.resolve(undefined);
    }
    return Promise.resolve(await PreloadManager.getDistinct(this._dataUnit, fieldName, options === null || options === void 0 ? void 0 : options.onlyLabel));
  }
  fetchData(filterTerm, fieldName) {
    return new Promise(resolve => {
      this._application.executeSelectDistinct(this._dataUnit, fieldName, filterTerm).then(result => {
        resolve(result.map(item => {
          const field = this._dataUnit.getField(fieldName);
          if (field.userInterface === UserInterface.SEARCH) {
            return Object.assign(Object.assign({}, JSON.parse(item)), { check: true });
          }
          return { value: item, label: this.formatLabel(fieldName, item), check: true };
        }));
      });
    });
  }
  sortItems(fieldName, items) {
    return InMemoryFilterColumnDataSource.defaultSorterMultSelectionOption(this._dataUnit, fieldName, items);
  }
}
