import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';

// Distance (in pixels) to begin next infinite-scroll load
const SCROLL_BUFFER = 500;

export default Component.extend({
  search: injectService(),
  similarChannels: injectService(),
  layout: injectService(),
  experiments: injectService(),
  tracking: injectService(),
  scrollBuffer: SCROLL_BUFFER,

  init() {
    this._super(...arguments);
    this.term = '';
    this.searchResults = {hits: []};
  },

  hasTerm: computed.notEmpty('term'),
  hits: computed.readOnly('searchResults.hits'),
  hitCount: computed.readOnly('hits.length'),
  hasHits: computed.bool('hitCount'),
  hasNoHits: computed.not('hasHits'),

  nextPage: computed('searchResults.page', function() {
    return this.get('searchResults.page') + 1;
  }),

  recommendedResults: [],
  hasRecommendedResults: computed.notEmpty('recommendedResults'),

  didInsertElement() {
    this._super(...arguments);
    this.$('input').focus();
  },

  clearResults() {
    this.set('searchResults', []);
  },

  actions: {
    loadMoreForType() {
      let page = this.get('nextPage');
      return this.query({page});
    },

    updateTerm(event) {
      let term = event.target.value;
      this.set('term', term);

      if (term) {
        this.query();
      } else {
        this.clearResults();
      }
    }
  },

  query(options = {}) {
    if (this.get('isLoading')) {
      return;
    }

    let term = this.get('term');
    this.set('isLoading', true);

    return this.get('search').queryForType('users', term, options).then((results) => {
      if (this.isDestroyed) { return; }

      this.set('searchResults', results['users']);
      this.set('isLoading', false);
      this.set('didError', false);
    }, (error) => {
      if (this.isDestroyed) { return; }

      this.set('didError', true);

      if (error.status && error.status >= 400) {
        return; /* Swallow this expected error */
      }
      throw error;
    });
  }
});
