/* globals _ */

/**
 * Adds a method that returns a promise which resolves when it and required child objects are loaded.
 * @class
 */
import Mixin from 'ember-metal/mixin';
import Ember from 'ember';

const { RSVP, on } = Ember;

export default Mixin.create({

  /** Configuration */

  _setDefaultLoadProfiles: on('init', function () {
    if (!this.get('loadProfiles')) {
      this.set('loadProfiles', {});
    }
  }),

  /** Publicly exposed properties and methods */

  /**
   * Adds a method that returns a promise which resolves when it and required child objects are loaded.
   * @class
   */

  /**
   * @override
   * @param options
   * @returns {RSVP.Promise}
   */
  load: function (options) {
    options = options || {};

    let self = this,
      loadProfile = this.get('loadProfiles')[options.profile] || {},
      loadPromises = [this._super(options)];

    _.each(loadProfile, function (cfg, childProperty) {
      let loadPromise = self.get(childProperty).load(cfg.profile);
      if (!cfg.nonBlocking) { loadPromises.push(loadPromise); }
    });

    return new RSVP.Promise(function (resolve, reject) {
      RSVP.all(loadPromises).then(function () { resolve(self); }, reject);
    });
  }
});
