import Ember from 'ember';
import computed from 'ember-computed';

const { RSVP, observer } = Ember;

export default {
  /** @function setOnReady
    * This function creates a property which is a promise that resolves to the value when the condition is met.
    * It's meant to be used when you need to wait for some condition (e.g. the model loaded) before doing some
    * action (e.g. track pageview).
    * See channel_controller.js for an example. */
  setOnReady: function (observable, options) {
    let extend            = {},
        resolvers         = [],
        NAME              = options.propertyName,
        CONDITION         = `${options.propertyName}__resolveCondition`,
        CONDITION_CHECKER = `${options.propertyName}__resolveConditionChecker`;

    extend[NAME] = computed(function () {
      let promise = new RSVP.Promise(function (resolve) {
        resolvers.push(resolve);
      });
      this.get(CONDITION_CHECKER).call(this);
      return promise;
    }).volatile();

    extend[CONDITION] = options.readyToResolveCondition || true;

    extend[CONDITION_CHECKER] = observer(CONDITION, function () {
      if (this.get(CONDITION)) {
        let value = options.value.call(this);
        resolvers.forEach(function (resolver) {
          resolver(value);
        });
        resolvers = [];
      }
    });

    observable.reopen(extend);
  }
};
