'use strict';

const filter = require('./filter-d5040f65.js');
const listFetchState = require('./list-fetch-state-a9e880b1.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$1) {
  if (!quickSearch || !filter$1) {
    return undefined;
  }
  return {
    operator: 'or',
    filters: quickSearch.fields.map(field => ({
      comparison: filter.Comparison.Contain,
      id: field.fieldId,
      value: filter$1,
    }))
  };
}
class DvnDataProvider {
  constructor(dataApi, collection, query, initialData, quickSearch) {
    this.didQuickSearchChangeAfterLastFetch = false;
    this.list = listFetchState.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.ListFetchState.init().afterFetch(response);
        this.didQuickSearchChangeAfterLastFetch = false;
        resolve(self.list.data);
      }, error => {
        self.list = listFetchState.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;
  }
}

const mentornityApiEndpoint = 'https://api.mentornity.com';
// export const mentornityApiEndpoint = 'http://localhost:1707';
const dataApiEndpoint = 'https://data.api.mentornity.com/prod/mentornity/';
// export const dataApiEndpoint = 'http://localhost:1003/mentornity/';

exports.DvnDataProvider = DvnDataProvider;
exports.dataApiEndpoint = dataApiEndpoint;
exports.mentornityApiEndpoint = mentornityApiEndpoint;
