import Component from 'ember-component';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import { htmlSafe } from 'ember-string';

/*
Infinite Scroll Slug is another attempt at a more generic infinite-scroll implementation.

It makes no assumptions about containers and uses visibility of an element to determine when to load more content.

Required Params
  `loadMore` which it will invoke when it enters the viewport.

Optional Params
  `buffer` how many pixels to reach up into content to trigger before you get to the bottom.
  `isLoading` a boolean signal that you've already loaded content and should not trigger another reload
  `contentLength` an integer for how many elemnts you have loaded we record these when dispatching load mores,
                  if the value is the same between loads then we stop dispatching requests for more content.
*/


export default Component.extend({
  attributeBindings: ['style'],
  impressionTracking: injectService(),

  buffer: 1,
  isLoading: false,
  lastContentLength: -1,

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

    this.get('impressionTracking').registerComponent(this, 'enteredViewport');
  },

  willDestroyElement() {
    this.get('impressionTracking').deregisterComponent(this);

    this._super(...arguments);
  },


  style: computed('buffer', function() {
    let buffer = this.get('buffer');
    let styles = {
      visibility: 'hidden',
      height: `${buffer}px`,
      'margin-top': `-${buffer}px`,
      'pointer-events': 'none'
    };

    let props = [];
    let keys = Object.keys(styles);
    for (let i = 0, len = keys.length; i < len; i++) {
      let key = keys[i];
      let val = styles[key];
      props.push(`${key}:${val}`);
    }

    return htmlSafe(props.join(';'));
  }),

  actions: {
    enteredViewport() {
      if (this.get('isLoading')) {
        return;
      }

      // This is where we check if we've grown since the last time we made a
      // request, if we haven't then don't make another one.

      // TODO: this might better belong as logic in the owning component since
      // this prevents us from handling error cases or cases in which new
      // content might *become* available (like comments)
      let contentLength = this.get('contentLength');
      if (this.get('lastContentLength') === contentLength) {
        return;
      }
      this.set('lastContentLength', contentLength);
      let loadMoreAction = this.get('loadMore');
      if (loadMoreAction) {
        loadMoreAction();
      }
    }
  }
});
