import documentReady from '@assets/js/documentReady';

var promotionList = window.promotions;

window.initCountdown = function(context) {
  context = context || document.body;

  if (typeof promotionList === 'undefined') {
    return;
  }

  for (let i = 0; i < promotionList.length; i++) {
    let PRODUCTS;
    const { order_promotion_id: id } = promotionList[i];

    if (typeof context.tagName === 'undefined') {
      let contextArray = Array.from(context);
      contextArray = contextArray.filter(({ nodeName }) => nodeName !== '#text');
      contextArray = contextArray.map(item => item.querySelector(`.js-promotion-id-${id}`));
      PRODUCTS = contextArray.filter(item => item != null);
    } else {
      PRODUCTS = context.querySelectorAll(`.js-promotion-id-${id}`);
    }

    const DATE_END = promotionList[i].date_end,
      DATE = /[0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}/g.test(DATE_END) ? DATE_END : `${DATE_END} 23:59:59`;

    countdown(DATE, function(countdownText) {
      for (let i = 0; i < PRODUCTS.length; i++) {
        PRODUCTS[i].innerHTML = countdownText;
      }
    });
  }
};

function countdown(endDate, func) {
  setInterval(function() {
    var miliseconds = moment(endDate).diff(moment());

    if (miliseconds < 0) {
      func('TERMINADA');
      return;
    }

    var duration = moment.duration(miliseconds);

    var months = duration.months();
    var days = duration.days();
    var hours = duration.hours();
    var minutes = duration.minutes();
    var seconds = duration.seconds();

    months = months ? months + 'm ' : '';
    days = days ? days + 'd ' : '';
    hours = ('0' + hours).slice(-2);
    minutes = ('0' + minutes).slice(-2);
    seconds = ('0' + seconds).slice(-2);

    func(months + days + hours + ':' + minutes + ':' + seconds);
  }, 1000);
}

documentReady(window.initCountdown);
