import $ from 'jquery';
import Slider from "../../sections/slider/slider";

class IHKTimeline {
  constructor(section) {
    section.addClass('initiated');
    this.section = section;
    this.itemSlider = section.find('.item-slider');
    this.yearsWrapper = section.find('.years-wrapper');
    this.yearsContainer = section.find('.years .container');
    this.years = this.yearsWrapper.find('.year-item');

    this.initResize();
    this.initDragging();
    this.buildSlider();
    this.initYearClick();
    this.activateItem(0);
    this.initSwitch();
    // this.initDocking();
  }

  initDocking() {
    this.winPosition = 0;
    this.secPosition = $(this.section.parent()).offset().top;
    this.scrolling = false;

    $(window).on('scroll', () => {
      if (this.scrolling) {
        return false;
      }
      const st = $(window).scrollTop();
      if (st > this.winPosition && st < this.secPosition - 100) {
        this.scrolling = true;
        $('html, body').animate({scrollTop: this.secPosition - 100}, 200, () => {
          this.scrolling = false;
        })
      }
      this.winPosition = st;
    })
  }

  initSwitch() {
    this.switches = this.section.siblings('.timeline-tabs').find('a');
    this.switchSlides = [];
    this.switches.each((index, tab) => {
      const href = tab.href;
      const id = href.substr(href.indexOf('#'));
      const target = parseInt($(id).attr('data-index'));
      this.switchSlides.push(target);
      tab.setAttribute('data-index', index);
      tab.setAttribute('data-target', target);
    })

    this.slider.section.on('slide-change', () => {
      this.switches.removeClass('active');
      const cs = this.slider.currentSlide;
      let i = this.switchSlides.length - 1;
      while (i >= 0) {
        if (cs >= this.switchSlides[i]) {
          this.switches.eq(i).addClass('active');
          break;
        }
        i--;
      }
    })

    this.switches.on('click', (e) => {
      e.preventDefault();
      const target = parseInt(e.currentTarget.getAttribute('data-target'));
      this.slider.goTo(target, false);
    })
  }

  initResize() {
    this.resizeTimeout = null;

    $(window).on('resize', () => {
      if (this.resizeTimeout) {
        clearTimeout(this.resizeTimeout);
      }
      this.resizeTimeout = setTimeout(() => {
        this.handleResize();
      }, 200)
    })

    this.handleResize();
  }

  handleResize() {
    this.containerWidth = this.yearsContainer.width();
    this.wrapperWidth = this.yearsWrapper.get(0).scrollWidth;
    this.scrollWidth = this.containerWidth - this.wrapperWidth;
    this.yearsWrapper.css({'width': this.wrapperWidth + 'px'});
  }

  initDragging() {
    this.dragOffset = 0;
    this.wrapperOffset = 0;

    this.yearsWrapper.get(0).onmousedown = (e) => { this.dragStart(e) };

    this.yearsWrapper.get(0).addEventListener('touchstart', (e) => {this.dragStart(e)});
    this.yearsWrapper.get(0).addEventListener('touchend', (e) => {this.dragEnd(e)});
    this.yearsWrapper.get(0).addEventListener('touchmove', (e) => {this.dragMove(e)});
  }

  dragStart(e) {
    this.dragOffset = 0;
    this.dragLast = 0;

    if (e.type === 'touchstart') {
      this.dragOrigin = e.touches[0].clientX;
    } else {
      this.dragOrigin = e.clientX;
      document.onmouseup = (e) => { this.dragEnd(e) };
      document.onmousemove = (e) => { this.dragMove(e) };
    }
  }

  dragMove(e) {
    if (e.type === 'touchmove') {
      this.dragLast = this.dragOffset;
      this.dragOffset = this.dragOrigin - e.touches[0].clientX;
    } else {
      this.dragLast = this.dragOffset;
      this.dragOffset = this.dragOrigin - e.clientX;
    }
    if (Math.abs(this.dragOffset) > 3) {
      this.yearsWrapper.addClass('dragging');
    }

    this.wrapperTarget = this.wrapperOffset - this.dragOffset;
    if (this.wrapperTarget > 0) {
      this.wrapperTarget = this.wrapperTarget / 4;
    } else if (this.wrapperTarget < this.scrollWidth) {
      this.wrapperTarget = this.scrollWidth + (this.wrapperTarget - this.scrollWidth) / 4;
    }

    this.yearsWrapper.css({'transform': 'translateX(' + this.wrapperTarget + 'px)'});
  }

  dragEnd() {
    const velocity = this.dragOffset - this.dragLast;
    if (Math.abs(velocity) > 5) {
      this.wrapperTarget = this.wrapperTarget - velocity * 10;
    }

    const bounceBack = this.checkScrollEnd();

    this.yearsWrapper.removeClass('dragging');
    this.wrapperOffset = this.wrapperTarget;

    if (bounceBack || Math.abs(velocity) > 5) {
      this.animateToPosition();
    }


    document.onmouseup = null;
    document.onmousemove = null;
  }

  animateToPosition() {
    this.yearsWrapper.addClass('animate');

    requestAnimationFrame(() => {
      this.yearsWrapper.css({'transform': 'translateX(' + this.wrapperTarget + 'px)'});
      setTimeout(() => {
        this.yearsWrapper.removeClass('animate');
      }, 300);
    })
  }

  buildSlider() {
    const slides = this.itemSlider.addClass('slider').appendTo(this.itemSlider);

    this.years.find('.items > li').each((i, li) => {
      const listItem = $(li);
      listItem.attr('data-index', i).find('.slide').appendTo(slides);
      listItem.on('click', () => {
        this.slider.goTo(i, true);
        this.activateItem(i);
      })
    })

    this.slider = new Slider(slides);
    this.slider.section.on('slide-change', () => {
      this.activateItem(this.slider.currentSlide);
    })

    this.slides = this.slider.section.find('.slide');
  }

  initYearClick() {
    this.years.children('.year').on('click', (e) => {
      $(e.currentTarget).next('.items').children('li').first().trigger('click');
    })
  }

  activateItem(index) {
    this.years.removeClass('current').find('li.active').removeClass('active');
    const yearItem = this.years.find('li[data-index="' + index + '"]').addClass('active').closest('.year-item').addClass('current');
    const ww = $(window).width();
    const iw = yearItem.outerWidth() * 1.5;

    if (yearItem.offset().left + iw > ww || yearItem.offset().left < 50) {
      this.wrapperOffset = this.wrapperTarget = yearItem.position().left * -1;
      this.checkScrollEnd();
      this.animateToPosition();
    }

    if (this.slides.eq(index).hasClass('has-image')) {
      this.slider.section.addClass('hide-circle');
    } else {
      this.slider.section.removeClass('hide-circle');
    }
  }

  checkScrollEnd() {
    if (this.wrapperTarget > 0) {
      this.wrapperTarget = 0;
      return true;
    } else if (this.wrapperTarget < this.scrollWidth) {
      this.wrapperTarget = this.scrollWidth;
      return true;
    }

    return false;
  }
}

export default IHKTimeline;

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.timeline:not(.initiated)').each((i, el) => {
    new IHKTimeline($(el));
  })
})
