import BasePaginator from './-base';
import injectService from 'ember-service/inject';
import { assign } from 'ember-platform';
import RSVP from 'rsvp';
import { assert } from 'ember-metal/utils';

export default BasePaginator.extend({
  store: injectService(),

  init() {
    this._super(...arguments);
    this.cursor = null;
    this.isComplete = false;
  },

  doQuery() {
    let type = this.relationshipType;
    let store = this.get('store');
    let params = assign({}, this.params, { limit: 20 });

    assert('Needs either a string `game` or string `channel` in params',
      typeof params.game === 'string' || typeof params.channel === 'string');

    if (this.cursor) {
      params.cursor = this.cursor;
    }

    // Borrowing playlists solution until paginator supports isComplete
    if (this.isComplete) {
      return RSVP.resolve({
        total: 0,
        items: []
      });
    }

    return store.query(type, params).then(result => {
      this.set('isComplete', !(result.meta.cursor));
      this.set('cursor', result.meta.cursor);

      return {
        //Clips doesn't return total at the moment but we need to return something
        total: result.meta.total,
        items: result
      };
    });
  }
});
