/**
 * @file
 * Javascript functionality for component launching soon.
 */

(function ($, Drupal) {

  'use strict';

  Drupal.componentLaunchingSoon = Drupal.componentLaunchingSoon || {};
  Drupal.behaviors.launching_soon = {
    attach: function (context) {
      Drupal.componentLaunchingSoon.launching_soon(context);
    }
  }
  Drupal.componentLaunchingSoon.launching_soon = function (context) {
    const $launching_soon =  $(once('launchingSoonItems', '.component-builder.component-item--type-launching-soon', context));
    if ($launching_soon.length > 0) {
      $launching_soon.each(function () {
        const $this = $(this);
        let $get_datetime = $this.find("div.field--name-field-launching-date > time").attr("datetime");
        let $countDownDate = new Date($get_datetime).getTime();
        let x = setInterval(function() {

          // Get today's date and time
          let $now = new Date().getTime();

          // Find the distance between now and the count down date
          let $distance = $countDownDate - $now;
          if ($distance <= 0) {
            // If the count down is finished, write some text
            if ($distance < 0) {
              clearInterval(x);
              $('div.component-item--type-launching-soon').addClass('launching-soon-expired');
              $this.find('div.component-item--content').before('<div class="expired">EXPIRED</div>')
            }
            $distance = 0
          }

          // Time calculations for days, hours, minutes and seconds
          let $days = Math.floor($distance / (1000 * 60 * 60 * 24));
          let $hours = Math.floor(($distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          let $minutes = Math.floor(($distance % (1000 * 60 * 60)) / (1000 * 60));
          let $seconds = Math.floor(($distance % (1000 * 60)) / 1000);

          // Display the result in the element
          $this.find("div.days > div.digit").text($days);
          $this.find("div.hours > div.digit").text($hours);
          $this.find("div.minutes > div.digit").text($minutes);
          $this.find("div.seconds > div.digit").text($seconds);

        }, 1000);
      })
    }
  }

})(jQuery, Drupal);
