/**
 * @file
 * JavaScript behaviors for filter by text.
 */

(function ($, Drupal, debounce, once) {
  /**
   * Filters the webform element list by a text input search string.
   *
   * The text input will have the selector `input.webform-form-filter-text`.
   *
   * The target element to do searching in will be in the selector
   * `input.webform-form-filter-text[data-element]`
   *
   * The text source where the text should be found will have the selector
   * `.webform-form-filter-text-source`
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the behavior for the webform element filtering.
   */
  Drupal.behaviors.webformFilterByText = {
    attach: function (context, settings) {
      $(once('webform-form-filter-text', 'input.webform-form-filter-text', context)).each(function () {
        var $input = $(this);
        $input.wrap('<div class="webform-form-filter"></div>');
        var $reset = $('<input class="webform-form-filter-reset" type="reset" title="Clear the search query." value="✕" style="display: none" />');
        $reset.insertAfter($input);
        var $table = $($input.data('element'));
        var $summary = $($input.data('summary'));
        var $noResults = $($input.data('no-results'));
        var $details = $table.closest('details');
        var $filterRows;

        var focusInput = $input.data('focus') || 'true';
        var sourceSelector = $input.data('source') || '.webform-form-filter-text-source';
        var parentSelector = $input.data('parent') || 'tr';
        var selectedSelector = $input.data('selected') || '';

        var hasDetails = $details.length;
        var totalItems;
        var args = {
          '@item': $input.data('item-singular') || Drupal.t('item'),
          '@items': $input.data('item-plural') || Drupal.t('items'),
          '@total': null
        };

        if ($table.length) {
          $filterRows = $table.find(sourceSelector);
          var off = /chrom(e|ium)/.test(window.navigator.userAgent.toLowerCase()) ? 'chrome-off-' + Math.floor(Math.random() * 100000000) : 'off';
          $input
            .attr('autocomplete', off)
            .on('keyup', debounce(filterElementList, 200))
            .keyup();

          $reset.on('click', resetFilter);

          // Make sure the filter input is always focused.
          if (focusInput === 'true') {
            setTimeout(function () {$input.trigger('focus');});
          }
        }

        /**
         * Reset the filtering
         *
         * @param {jQuery.Event} e
         *   The jQuery event for the keyup event that triggered the filter.
         */
        function resetFilter(e) {
          $input.val('').keyup();
          $input.trigger('focus');
        }

        /**
         * Filters the webform element list.
         *
         * @param {jQuery.Event} e
         *   The jQuery event for the keyup event that triggered the filter.
         */
        function filterElementList(e) {
          var query = $(e.target).val().toLowerCase();

          // Filter if the length of the query is at least 2 characters.
          if (query.length >= 2) {
            // Reset count.
            totalItems = 0;
            if ($details.length) {
              $details.hide();
            }
            $filterRows.each(toggleEntry);

            // Announce filter changes.
            // @see Drupal.behaviors.blockFilterByText
            Drupal.announce(Drupal.formatPlural(
              totalItems,
              '1 @item is available in the modified list.',
              '@total @items are available in the modified list.',
              args
            ));
          }
          else {
            totalItems = $filterRows.length;
            $filterRows.each(function (index) {
              $(this).closest(parentSelector).show();
              if ($details.length) {
                $details.show();
              }
            });
          }

          // Set total.
          args['@total'] = totalItems;

          // Hide/show no results.
          $noResults[totalItems ? 'hide' : 'show']();

          // Hide/show reset.
          $reset[query.length ? 'show' : 'hide']();

          // Update summary.
          if ($summary.length) {
            $summary.html(Drupal.formatPlural(
              totalItems,
              '1 @item',
              '@total @items',
              args
            ));
            $summary[totalItems ? 'show' : 'hide']();
          }

          /**
           * Shows or hides the webform element entry based on the query.
           *
           * @param {number} index
           *   The index in the loop, as provided by `jQuery.each`
           * @param {HTMLElement} label
           *   The label of the webform.
           */
          function toggleEntry(index, label) {
            var $label = $(label);
            var $row = $label.closest(parentSelector);

            var textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
            var isSelected = (selectedSelector && $row.find(selectedSelector).length) ? true : false;

            var isVisible = textMatch || isSelected;
            $row.toggle(isVisible);
            if (isVisible) {
              totalItems++;
              if (hasDetails) {
                $row.closest('details').show();
              }
            }
          }
        }
      });
    }
  };

})(jQuery, Drupal, Drupal.debounce, once);
