/**
 * @file
 * Select2 integration.
 */
(function ($, drupalSettings, Sortable, once) {
  'use strict';

  Drupal.behaviors.select2 = {
    attach: function (context) {
      $(once('select2-init', '.select2-widget', context)).each(function () {
        var config = $(this).data('select2-config');
        config.createTag = function (params) {
          var term = $.trim(params.term);
          if (term === '') {
            return null;
          }
          return {
            id: '$ID:' + term,
            text: term
          };
        };
        config.templateSelection = function (option, container) {
          // The placeholder doesn't have value.
          if ('element' in option && 'value' in option.element) {
            // Add option value to selection container for sorting.
            $(container).data('optionValue', option.element.value);
          }
          return option.text;
        };
        if (Object.prototype.hasOwnProperty.call(config, 'ajax')) {
          config.ajax.data = function (params) {
            var selected = [];
            if (Array.isArray($(this).val())) {
              selected = $(this).val();
            }
            else if ($(this).val() !== '') {
              selected = [$(this).val()];
            }
            return $.extend({}, params, {
              q: params.term,
              selected: selected.filter(function (selected) {
                return !selected.startsWith('$ID:');
              })
            });
          };
        }
        $(this).data('select2-config', config);

        // Emit an event, that other modules have the chance to modify the
        // select2 settings. Make sure that other JavaScript code that rely on
        // this event will be loaded first.
        // @see: modules/select2_publish/select2_publish.libraries.yml
        $(this).trigger('select2-init');
        config = $(this).data('select2-config');

        // If config has a dropdownParent property, wrap it a jQuery object.
        if (Object.prototype.hasOwnProperty.call(config, 'dropdownParent')) {
          config.dropdownParent = $(config.dropdownParent);
        }
        $(this).select2(config);

        // Copied from https://github.com/woocommerce/woocommerce/blob/master/assets/js/admin/wc-enhanced-select.js#L118
        if (config.multiple) {
          var $select = $(this);
          var $list = $select.next('.select2-container').find('ul.select2-selection__rendered');
          Sortable.create($list[0], {
            draggable: 'li:not(.select2-search)',
            onEnd: function (event) {
              if (event.newIndex != event.oldIndex) {
                $($list.find('.select2-selection__choice').get().reverse()).each(function () {
                  $select.prepend($select.find('option[value="' + $(this).data('optionValue') + '"]').first());
                });
              }
            }
          });
        }
      });
    }
  };

})(jQuery, drupalSettings, Sortable, once);
