/**
 * Triggers the contents to expire when the instance is asked to load if it has stale data.  Expiration time is configurable.
 * @class
 */
import Mixin from 'ember-metal/mixin';
import Ember from 'ember';
import computed from 'ember-computed';

const { Evented, on } = Ember;

export default Mixin.create(Evented, {
  /** Configuration */

  expiration: undefined, /** in milliseconds */

  /** Publicly exposed properties and methods */

  isExpired: computed(function () {
    if (!this.get('expiration')) {
      return false;
    }
    return new Date().getTime() - (this.get('_lastLoadTime') || 0) > this.get('expiration');
  }).volatile(),

  /** Private helpers */

  /**
   * @override
   * @returns {*}
   * @private
   */
  _shouldLoad: function () {
    return this._super() || this.get('isExpired');
  },

  _setLastLoadTime: on('loadSuccess', function () {
    this.set('_lastLoadTime', new Date().getTime());
  })
});
