// import $ from 'jquery';
const $ = require('jquery');
import Slider from './slider';
import 'jquery.easing';

class QuickFacts {
  constructor(section) {
    this.section = section.addClass('initiated');
    this.initSlides();
    this.slider = new Slider(section.find('.slider'));
    this.stringLength = 0;

    this.slider.section.on('in-viewport slide-change', () => {
      const curr = this.slider.currentSlide;
      if (this.slides[curr].hasCounter) {
        this.startCounter(curr);
      }
    })
  }

  initSlides() {
    this.slides = [];
    this.section.find('.slider').children().each((i, element) => {
      const span = $(element).find('.counter');
      const c = {};
      c.hasCounter = span.length === 1;
      if (c.hasCounter) {
        c.element = span;
        c.from = parseFloat(span.attr('data-from'));
        c.to = parseFloat(span.attr('data-to'));
        c.duration = parseFloat(span.attr('data-duration')) * 1000;
        c.decimals = parseFloat(span.attr('data-decimals'));
        c.animation = $({num: c.from});
      }
      this.slides.push(c);
    })
  }

  startCounter(index) {
    const t = this;
    const c = this.slides[index];

    c.stringLength = 0;
    c.animation.stop();
    c.animation = $({num: c.from});
    t.setText(c, t.formatNumber(c.from, c.decimals));

    c.animation.animate({num: c.to}, {
      duration: c.duration,
      easing: 'easeOutCubic',
      step(num) {
        t.setText(c, t.formatNumber(num, c.decimals));
      },
      complete() {
        t.setText(c, t.formatNumber(c.to, c.decimals));
      }
    })
  }

  setText(counter, str) {
    if (str.length !== counter.stringLength) {
      counter.element.css('width', 'auto');
      counter.element.text(str);
      counter.element.css('width', Math.round(counter.element.outerWidth()) + 'px');
      counter.stringLength = str.length;
    }
    else {
      counter.element.text(str);
    }
  }

  formatNumber(num, decimals) {
    return new Intl.NumberFormat('de-DE',{
      minimumFractionDigits: decimals,
      maximumFractionDigits: decimals,
    }).format(num);
  }
}


$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.quick-facts:not(.initiated)').each(function() {
    new QuickFacts($(this));
  });
});
