const $ = require('jquery');
class EventPagination {
  constructor(list) {
    if (!list.data('pagination') || list.data('items') >= list.children().length) {
      list.closest('.events-wrapper').next('.events-actions').find('.prev, .next').remove();
      return false;
    }
    this.list = list.addClass('initiated');
    this.wrapper = list.closest('.events-wrapper');
    this.items = list.children();
    this.current = 0;
    this.resizeTimer = null;
    this.scroll = this.list.data('scroll');
    this.show = this.list.data('items');

    if (!this.scroll) {
      this.scroll = this.show;
    }

    this.initButtons();
    this.goTo(0);
    this.initResize();
  }

  initResize() {
    $(window).on('resize', () => {
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer);
      }
      this.resizeTimer = setTimeout( () => {
        this.goTo(this.current);
      }, 250)
    })
  }

  initButtons() {
    this.prevBtn = this.wrapper.next('.events-actions').find('.prev');
    this.nextBtn = this.wrapper.next('.events-actions').find('.next');

    this.nextBtn.on('click', (e) => {
      e.preventDefault();
      this.next();
    })
    this.prevBtn.on('click', (e) => {
      e.preventDefault();
      this.prev();
    })
  }

  next() {
    if (this.current + this.scroll + this.show < this.items.length) {
      this.goTo(this.current + this.scroll);
      this.nextBtn.removeClass('disabled').removeAttr('disabled', 'disabled');
    }
    else {
      this.goTo(this.items.length - this.show);
      this.nextBtn.addClass('disabled').attr('disabled', 'disabled');
    }

    this.prevBtn.removeClass('disabled').removeAttr('disabled', 'disabled');
  }

  prev() {
    if (this.current - this.scroll > 0) {
      this.goTo(this.current - this.scroll);
      this.prevBtn.removeClass('disabled').removeAttr('disabled', 'disabled');
    }
    else {
      this.goTo(0);
      this.prevBtn.addClass('disabled').attr('disabled', 'disabled');
    }

    this.nextBtn.removeClass('disabled').removeAttr('disabled', 'disabled');
  }

  goTo(firstID) {
    const firstItem = this.items.eq(firstID);
    const lastItem = this.items.eq(firstID + this.show - 1);

    this.wrapper.css('height', (lastItem.position().top - firstItem.position().top + lastItem.outerHeight()) + 'px');
    this.list.css('transform', 'translate3d(0, -' + firstItem.position().top + 'px, 0');

    this.items.each((i, el) => {
      if (i < firstID || i > firstID + this.show - 1) {
        $(el).find('a').attr('tabindex', '-1');
      }
      else {
        $(el).find('a').removeAttr('tabindex');
      }
    })

    this.current = firstID;
  }
}

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.events-list[data-pagination="true"]:not(.initiated)').each(function(i) {
    new EventPagination($(this));
  });
})
