import Helper from 'ember-helper';
import Model from 'ember-data/model';
import get from 'ember-metal/get';

/* This is one answer to Ember Data's optimistic presentation of attributes.
 * This helper reads attributes from a DS.Model's `data` property to show the
 * "committed" attribute in a template. `data` is a private property that holds
 * the last attributes that were aknowledged by the server. These are the same
 * attributes one would see if they called rollbackAttributes().
 */
export default Helper.extend({
  init() {
    this._super(...arguments);
    this.model = null;
  },

  compute([model, key]) {
    if (this.model) {
      this._removeListeners();
    }

    this.model = model;

    if (this.model instanceof Model) {
      this.model.on('didCreate', this, 'recompute');
      this.model.on('didLoad', this, 'recompute');
      this.model.on('didUpdate', this, 'recompute');

      return model.get('data')[key];
    }

    return get(model, key);
  },

  _removeListeners() {
    if (this.model instanceof Model) {
      this.model.off('didCreate', this, 'recompute');
      this.model.off('didLoad', this, 'recompute');
      this.model.off('didUpdate', this, 'recompute');
    }
  },

  willDestroy() {
    this._super(...arguments);
    this._removeListeners();
  }
});
