import Ember from 'ember';
import _ from 'lodash';

export default Ember.Route.extend({

  player: Ember.inject.service(),
  filter: Ember.inject.service(),

  index: 0,
  limit: 40,
  sort: 'alphabetical',
  isFetching: false,

  themes: null,
  total: 0,

  model() {
    var filterQueryParams = _.clone(this.get('filter').get('queryParamsValues'));
    var promise = this.get('store').query('theme', _.merge(filterQueryParams, {
      'limit': this.get('limit'),
      'index': this.get('index'),
      'sort': this.get('sort')
    }));
    promise.then(response => {
      this.set('themes', response.get('content'));
      this.set('total', response.get('meta').total);
    });
    return promise;
  },

  activate: function () {
    this.get('player').set('window', false);
  },

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

  actions: {

    loadMore: function() {
      if(this.get('isFetching') || (this.get('themes').length === this.get('total'))) {
        return;
      }
      this.set('isFetching', true);
      this.set('index', this.get('index') + 1);
      var filterQueryParams = _.clone(this.get('filter').get('queryParamsValues'));
      this.get('store').query('theme', _.merge(filterQueryParams, {
        'limit': this.get('limit'),
        'index': this.get('index'),
        'sort': this.get('sort')
      })).then(response => { // success
        this.get('themes').pushObjects(response.get('content'));
        this.set('isFetching', false);
      }, () => { // fail
        this.set('isFetching', false);
      });
    },

    setSortQueryparams: function (sort) {
      this.set('sort', sort);
      this.set('index', 0);
      this.refresh();
      return false;
    },

  }

});
