import EmberObject from 'ember-object';
import { assert } from 'ember-metal/utils';

export default EmberObject.extend({
  init() {
    this._super(...arguments);
    this.total = 0;
    this.items = [];
  },

  doQuery() {
    throw new Error('must implement doQuery on Paginator');
  },

  fetchNextPage() {
    this.set('items.isLoading', true);
    return this.doQuery().then(({ total, items }) => {
      if (this.isDestroyed) { return; }
      assert('#doQuery must resolve a promise with property items', !!items);

      if (total) {
        this.set('total', total);
      }
      items.forEach(r => this.items.pushObject(r));
      return this;
    }).finally(() => {
      this.set('items.isLoading', false);
    });
  }
});
