import Ember from 'ember';

export default Ember.Component.extend({

    classNames: ['sorting-component'],

    filter: Ember.inject.service(),

    isAlphabetical: true,
    isPopularity: Ember.computed('isAlphabetical', function() { return !this.get('isAlphabetical'); }),

    minimum: Ember.computed('themes.[]', function() { return Math.min(...this.get('themes').mapBy('count')); }),
    maximum: Ember.computed('themes.[]', function() { return Math.max(...this.get('themes').mapBy('count')); }),

    more: true,
    hasMore: Ember.computed('themes.[]', 'total', function() {
      let themes = this.get('themes');
      let total = this.get('total');
      return !themes || themes.get('length') < total;
    }),

    themes: null,
    total: Ember.computed('themes.[]', function() {
      let themes = this.get('themes');
      return themes?themes.get('meta').total:0;
    }),

    scrolling: function(target) {
        if(Ember.$(target).scrollTop() !== 0 ) {
            if(Ember.$(target).scrollTop() + Ember.$(target).height() > Ember.$(target).get(0).scrollHeight - 50) {
                this.triggerAction({ action:'loadMore', target: this });
            }
        }
    },

    moreObserver: Ember.observer('more', function() {
      let more = this.get('more');
      let self = this;
      if(!more) {
        this.set('scrollHandler', this.$('.tags').on('scroll', function(event) { Ember.run.throttle(self, function() { self.scrolling(event.target); }, 300); }));
      } else {
        this.$('ul').off('scroll', this.get('scrollHandler'));
      }
    }),

    filterObserver: Ember.observer('filter.date.[]', 'filter.discourse.[]', 'filter.language', 'filter.location', 'filter.theme.[]', function() {
      this.set('more', true);
    }),

    actions: {

        setQueryParameters: function(id) {
            this.get('filter').setFilter('theme', id);
        },

        sortBy: function (type) {
            if(type === 'alphabetical') {
                this.set('isAlphabetical', true);
                this.sendAction('sort', 'alphabetical');
            } else {
                this.set('isAlphabetical', false);
                this.sendAction('sort', 'descending');
            }
            this.set('more', true);
        },

        loadMore: function() {
            this.sendAction('load');
            this.set('more', false);
        }

    }

});
