import $ from 'jquery';
import run from 'ember-runloop';
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import observer from 'ember-metal/observer';

export default Component.extend({
  itemWidth: null, // must be provided
  showGoRight: false,
  showGoLeft: false,

  layout: injectService(),

  didInsertElement: function () {
    this._initFilters();
    run.schedule('afterRender', this, this.calculateShowGoRight);
  },

  _initFilters: function () {
    this.$('.js-goright').on('click', () => {
      this.throttleTask('goRight', 600);
    });

    this.$('.js-goleft').on('click', () => {
      this.throttleTask('goLeft', 600);
    });
  },

  goRight() {
    let itemWidth = this.get('itemWidth');
    let p = $('.js-filter-list ul').position();
    let n = Math.floor($('.js-filter-list-contain').outerWidth() / itemWidth) * itemWidth;
    let offset = p.left - n;

    if (0 - offset >= $('.js-filter-list ul').outerWidth() - n) {
      this.set('showGoRight', false);
    }

    $('.js-filter-list ul').css('left', offset);
    this.set('showGoLeft', true);
  },

  goLeft() {
    let itemWidth = this.get('itemWidth');
    let p = $('.js-filter-list ul').position();
    let n = Math.floor($('.js-filter-list-contain').outerWidth() / itemWidth) * itemWidth;
    let offset = p.left + n;

    if (offset >= 0) {
      this.set('showGoLeft', false);
    }

    $('.js-filter-list ul').css('left', offset);

    this.set('showGoRight', true);
  },

  calculateShowGoRight: observer('layout.contentWidth', 'items.[]', function () {
    if (this.isDestroyed) {
      return;
    }

    let listWidth = this.$('.js-filter-list ul').outerWidth();
    let contentWidth = this.get('layout.contentWidth');
    let show = listWidth > contentWidth;

    this.set('showGoRight', show);
  })
});
