(function ($, Drupal){
    'use strict';
    Drupal.behaviors.filter_calendar_performances = {
      attach: function (context) {
        //Button calendar
        once('toggle-calendar-filter-button', '.button-calendar-filter', context).forEach(selector => {
          const $input = $(selector);
          $input.click(function (e) {
            e.preventDefault();
            $('.my-datepicker-calendar-filter-performances').toggleClass('d-none');
          });
        });

        // Clean filter
        once('clean-filter-button', '.button-clean-filter', context).forEach(selector => {
          const $input = $(selector);
          $input.click(function (e) {
            e.preventDefault();
            $('input[data-drupal-selector="edit-field-performance-date-value-1"]').val('');
            $('input[data-drupal-selector="edit-field-performance-date-value"]').val('');
            $('#edit-submit-calendar-filter-performances').click();
            $('.button-clean-filter').addClass('d-none');
            $('.dp-highlight').removeClass('dp-highlight');
          });
        });

        // Close Toggle Calendar
        function closeToggleCalendar(selector) {
          $(selector).click(function (e) {
            const $target = $(e.target);
            if (
              !$target.is('.button-calendar-filter')
              && !$target.is("[class|='ui-datepicker']")
              )
            {
              $('.my-datepicker-calendar-filter-performances').addClass('d-none');
            }
          });
        }

        if (context.tagName == 'BODY') {
          closeToggleCalendar(context);
        } else {
          once('close-toggle', 'body', context).forEach(selector => {
            closeToggleCalendar(selector);
          });
        }

        // Calendar
        once('datepicker-calendar-filter', '.my-datepicker-calendar-filter-performances', context).forEach(selector => {
          const $dateMaxField = $('input[data-drupal-selector="edit-field-performance-date-value-1"]');
          const $dateMinField = $('input[data-drupal-selector="edit-field-performance-date-value"]');
          const $datepicker = $(selector);
          $datepicker.datepicker({
            changeMonth: false,
            changeYear: false,
            minDate: 0,
            numberOfMonths: [1,1],
            yearRange: "c:c+3",
            monthNames: [
              Drupal.t('January',  { context: 'Long month name'}),
              Drupal.t('February', { context: 'Long month name'}),
              Drupal.t('March',  { context: 'Long month name'}),
              Drupal.t('April', { context: 'Long month name'}),
              Drupal.t('May', { context: 'Long month name'}),
              Drupal.t('June', { context: 'Long month name'}),
              Drupal.t('July', { context: 'Long month name'}),
              Drupal.t('August', { context: 'Long month name'}),
              Drupal.t('September', { context: 'Long month name'}),
              Drupal.t('October',  { context: 'Long month name'}),
              Drupal.t('November', { context: 'Long month name'}),
              Drupal.t('December',  { context: 'Long month name'}),
            ],
            firstDay: 1,
            beforeShowDay: function(date) {
              let date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMinField.val());
              let date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMaxField.val());
              let $allSelected = $('.dp-highlight');
              let cssClass = '';

              if (date1 && date.getTime() == date1.getTime()) {
                cssClass += "dp-highlight first-selected";
                if (date2 && dateWithoutTime($dateMaxField.val()) != dateWithoutTime($dateMinField.val())) {
                  cssClass += " first-element";
                }
              }
              else if (date2 && date.getTime() == date2.getTime()) {
                cssClass += "dp-highlight last-selected";
              }
              else if (date1 && date2 && date.getTime() > date1.getTime() && date.getTime() < date2.getTime()) {
                cssClass += "dp-highlight";
              }
              let result = [true, cssClass];
              return result;
            },
            onSelect: function(dateText, inst) {
              let date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMinField.val());
              let date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMaxField.val());
              let selectedDate = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
              let hour = ' 23:59:59';
              $('.button-clean-filter').removeClass('d-none');
              if (Date.parse(selectedDate) == Date.parse(date1)) {
                $dateMaxField.val('');
                $dateMinField.val('');
                $('.button-clean-filter').addClass('d-none');
              } else if (!date1 && !date2) {
                $dateMinField.val(dateText);
                $dateMaxField.val(dateText+hour);
              } else if (dateWithoutTime($dateMinField.val()) == dateWithoutTime($dateMaxField.val())) {
                if (selectedDate < date1 ) {
                  $dateMaxField.val($dateMinField.val()+hour);
                  $dateMinField.val(dateText);
                } else {
                  $dateMaxField.val(dateText+hour);
                }
              } else if (!date1 || date2) {
                $dateMinField.val(dateText);
                $dateMaxField.val(dateText+hour);
              }
              let $allSelected = $('.dp-highlight');
              $allSelected
                .removeClass('first-selected')
                .removeClass('last-selected');
              if ($allSelected.length > 0) {
                $allSelected.first().addClass('first-selected');
                $allSelected.last().addClass('last-selected');
              }
              $('#edit-submit-calendar-filter-performances').click();
            },
          });
        });

        function dateWithoutTime(dt) {
          dt = dt.split(' ');
          return dt[0];
        }
      }
    }
  })(jQuery, Drupal);


