import './paragraph.statistic.scss';

import { CountUp } from 'countup.js';

Drupal.behaviors.statistic = {
  attach(context) {
    const STATISTICS = document.querySelectorAll('[data-js="statistic"]');

    let countUpOptions = {
      duration: 2,
      enableScrollSpy: true,
      scrollSpyOnce: true,
    };

    once('statistic', STATISTICS, context).forEach(statistic => {
      let container = statistic.querySelector('.statistic__number');
      let containerNumberOriginal = container.getAttribute('data-number');

      // Create an array of values based on the regex.
      let values = containerNumberOriginal.split(/([:|/|])/);

      values.forEach(value => {
        let spanEl = document.createElement('span');

        spanEl.innerText = value;
        container.appendChild(spanEl);

        // The "value" is a number, process it.
        if (!isNaN(parseFloat(value))) {
          let hasComma = value.indexOf(',') != -1 ? true : false;
          let decimalPosition = value.indexOf('.');
          let decimalPlaces = (decimalPosition !== -1)
            // Remove 1 since the decimalPosition counts the decimal.
            ? (value.length - decimalPosition) - 1
            : 0;

          countUpOptions['hasComma'] = hasComma;
          countUpOptions['decimalPlaces'] = decimalPlaces;

          new CountUp(spanEl, value, countUpOptions);
        }
      })
    })
  }
}
