export default class WsCarouselController {
  activeSlideNum = 0;
  totalSlideCount = 0;

  static $inject = ['$timeout'];
  constructor($timeout) {
    this.$timeout = $timeout;
  }

  $postLink() {
    this.$timeout(() => {
      this.totalSlideCount = this._reflowSlides();
      this.activeSlideNum = 0;
      this._showSlide(this.activeSlideNum);
    }, 0);
  }

  showNextSlide = () => {
    this._showSlide(++this.activeSlideNum);
  }

  showPreviousSlide = () => {
    this._showSlide(--this.activeSlideNum);
  }

  canGoForward = () => this.activeSlideNum < this.totalSlideCount - 1;
  canGoBack = () => this.activeSlideNum > 0;

  getSelectorRange = () => new Array(this.totalSlideCount).map((v, i) => i);

  isActiveSlide = slideNum => slideNum === this.activeSlideNum;
  setActiveSlide = (slideNum) => {
    if (slideNum !== this.activeSlideNum) {
      this.activeSlideNum = slideNum;
      this._showSlide(slideNum);
    }
  }

  _reflowSlides = () => {
    const slideContainer = angular.element('.slide-container');
    const slideCount = slideContainer.children().length;

    slideContainer
      .css('width', `${100 * slideCount}%`)
      .children()
      .css('width', `${100 / slideCount}%`);

    return slideCount;
  }

  _showSlide = (slideNum) => {
    angular.element('.slide-container')
      .css('transform', `translate(${(-100 * slideNum) / this.totalSlideCount}%)`)
      .children()
      .removeClass('next-slide previous-slide current-slide')
      .addClass(i => i < slideNum ? 'previous-slide' : '')
      .addClass(i => i === slideNum ? 'current-slide' : '')
      .addClass(i => i > slideNum ? 'next-slide' : '');

    if (this.onSlideActivated) {
      this.onSlideActivated({ slideIndex: slideNum });
    }
  }
}
