import Service from 'ember-service';
import getOwner from 'ember-owner/get';
import { assert } from 'ember-metal/utils';

export default Service.extend({
  _getTypeForRelationship(model, relationshipName) {
    // PRIVATE API TODO FIND A BETTER WAY
    return model._internalModel._relationships.get(relationshipName).relationshipMeta.type;
  },

  createPageForType(factoryName, options = {}) {
    let pageFactory = getOwner(this)._lookupFactory(`paginator:${factoryName}`);
    return pageFactory.create(options);
  },

  /**
   * Instantiate a paginator object for a given `model` and `relationshipName`, using the specified `pageFactory`.
   * Example, given a model object called `channel` with a defined relationship `following: hasMany('channel')`,
   * and a paginator defined in `app/paginators/follow`, get a paginator object with:
   * `service.paginatorFor({ model: channel, relationshipName: 'following', pageFactory: 'follow' })`
   *
   * @method paginatorFor
   * @param {Model} model
   * @param {String} relationshipName
   * @param {String} pageFactory corresponds to a paginator file in `app/paginators/${pageFactory}`
   * @return {Paginator} paginator object with empty array of items.
   */
  paginatorFor({model, relationshipName, pageFactory, params}) {
    assert('#paginatorFor options expect a model property', !!model);
    assert('#paginatorFor options expect a relationshipName property', !!relationshipName);
    assert('#paginatorFor options expect a pageFactory property', !!pageFactory);

    let relationshipType = this._getTypeForRelationship(model, relationshipName);

    return this.createPageForType(pageFactory, {
      model,
      relationshipName,
      relationshipType,
      params
    });
  }
});
