import Component from 'ember-component';

// Inspired by http://coryforsyth.com/2013/07/28/infinite-scrolling-with-ember-js/
export default Component.extend({
  windowSelector: '',
  contentSelector: '',

  hasScrolledToBottom: false,

  didInsertElement() {
    this._super(...arguments);

    let windowSelector = this.get('windowSelector');
    let contentSelector = this.get('contentSelector');

    this.$window = this.$(windowSelector);
    this.$content = this.$(contentSelector);

    this.addEventListener(windowSelector, 'scroll', () => {
      if (this.get('hasScrolledToBottom')) { return; }

      if (this._isScrolledToBottom()) {
        this.set('hasScrolledToBottom', true);
      }
    });
  },

  _isScrolledToBottom() {
    let margin = this.$window.innerHeight() - this.$window.height();
    let distanceToViewportTop = margin + this.$content.height() - this.$window.height();
    let distanceToBottom =  distanceToViewportTop - this.$window.scrollTop();

    return distanceToBottom < 1;
  }
});
