import { DataModel } from './data-model';
export class ListFetchState {
  constructor(data, meta, isPending = false, error) {
    this.beforeFetch = () => new ListFetchState(this.data, this.meta, true, undefined);
    this.afterFetch = (response, append = true) => {
      var _a;
      const data = (this.data && append)
        ? [...this.data, ...DataModel.decodeList(response.results)]
        : DataModel.decodeList(response.results);
      let meta = this.meta; // keep existing meta if the later ones don't have total
      if ((_a = response.meta) === null || _a === void 0 ? void 0 : _a.total) {
        meta = response.meta;
      }
      else if (!meta && response.results.length === 0) {
        // generate a meta to indicate that the end is reached when there is no items left
        meta = {
          total: data.length
        };
      }
      return new ListFetchState(data, meta, false, undefined);
    };
    this.afterFetchError = (error) => new ListFetchState(this.data, this.meta, false, error);
    this.afterUpdateItem = (itemId, data) => new ListFetchState(this.data ? [...this.data].map(item => {
      if (item._id === itemId) {
        return (Object.assign(Object.assign({}, item), data));
      }
      return item;
    }) : this.data, this.meta, false, undefined);
    this.isEndReached = () => (this.data && this.meta) ? this.data.length >= this.meta.total : false;
    this.data = data;
    this.error = error;
    this.isPending = isPending;
    this.meta = meta;
  }
}
ListFetchState.init = () => new ListFetchState();
