import { C as Comparison } from './filter-cbaa3d7d.js';
import { L as ListFetchState } from './list-fetch-state-e772aa74.js';

function buildQuery(query, quickFilter) {
  let queryFilter = query ? query.filter : undefined;
  if (quickFilter) {
    if (query && query.filter) {
      queryFilter = {
        operator: 'and',
        filters: [query.filter, quickFilter]
      };
    }
    else {
      queryFilter = quickFilter;
    }
  }
  return queryFilter;
}
function generateQuickSearchFilters(quickSearch, filter) {
  if (!quickSearch || !filter) {
    return undefined;
  }
  return {
    operator: 'or',
    filters: quickSearch.fields.map(field => ({
      comparison: Comparison.Contain,
      id: field.fieldId,
      value: filter,
    }))
  };
}
class DvnDataProvider {
  constructor(dataApi, collection, query, initialData, quickSearch) {
    this.didQuickSearchChangeAfterLastFetch = false;
    this.list = ListFetchState.init();
    this.collection = collection;
    this.query = query;
    this.initialData = initialData;
    this.quickSearch = quickSearch;
    this.api = dataApi;
  }
  getInitialData() {
    return Promise.resolve(this.initialData);
  }
  getData() {
    const { api, collection, query, quickSearchText } = this;
    const self = this;
    return new Promise(((resolve, reject) => {
      if (self.list.data && !this.didQuickSearchChangeAfterLastFetch) {
        // return already fetched data
        resolve(self.list.data);
        return;
      }
      const queryFilter = buildQuery(query, generateQuickSearchFilters(this.quickSearch, quickSearchText));
      api.query(collection, {
        fields: query.fields,
        filter: queryFilter,
        limit: 50,
        skip: 0,
        sort: query.sort,
      }).then(response => {
        self.list = ListFetchState.init().afterFetch(response);
        this.didQuickSearchChangeAfterLastFetch = false;
        resolve(self.list.data);
      }, error => {
        self.list = ListFetchState.init().afterFetchError(error);
        reject(error);
      });
    }));
  }
  setInitialData(initialData) {
    this.initialData = initialData;
  }
  setQuickSearchText(text) {
    this.quickSearchText = text;
    this.didQuickSearchChangeAfterLastFetch = true;
  }
  getQuickSearchText() {
    return this.quickSearchText;
  }
  isQuickSearchEnabled() {
    return !!this.quickSearch;
  }
}

export { DvnDataProvider as D };
