const selects = (bulletinwpAdmin) => {
  jQuery(document).ready(function ($) {
    const selectResolveWidthTemplate = function (tag, container) {
      // here we are finding option element of tag and
      // if it has property 'locked' we will add class 'locked-tag'
      // to be able to style element in select
      const $option = $('.select2 option[value="'+tag.id+'"]');
      if ($option.attr('locked')){
        $(container).addClass('locked-tag');
        tag.locked = true;
      }
      return tag.text;
    };

    const selectResolveWidthTemplateResult = function (tag, container) {
      const $option = $('.select2 option[value="'+tag.id+'"]');
      if ($option.attr('locked')){
        $(container).addClass('locked-tag');
        tag.locked = true;
      }
      return tag.text;
    };

    const selectIconsTemplateResult = function (state, container) {
      if (!state.id) {
        return state.text;
      }

      container.style.backgroundImage = `url(${state.element.getAttribute('data-image-url')})`;

      const iconSet = bulletinwpAdmin.find('input[name="addIcon"]:checked').val();

      if (
        (iconSet === 'from-set' && state.element.getAttribute('data-image-set') === 'original') ||
        (iconSet === 'from-set-solid' && state.element.getAttribute('data-image-set') === 'solid') ||
        (iconSet === 'from-set-outline' && state.element.getAttribute('data-image-set') === 'outline')
      ) {
        return state.text;
      }
    };

    const select2 = bulletinwpAdmin.find('select.select2');

    if (select2.length) {
      select2.each(function () {
        const _this = $(this);

        // API Defaults refer to: https://select2.org/configuration/options-api
        const minimumResultsForSearch = _this.hasClass('infinity') ? Infinity : 0;
        const tags = _this.hasClass('select-resolve-width') ? true : false;
        const templateSelection = _this.hasClass('select-resolve-width')
          ? selectResolveWidthTemplate
          : undefined;
        const templateResult = _this.hasClass('select-resolve-width')
          ? selectResolveWidthTemplateResult
          : _this.hasClass('icons-select')
            ? selectIconsTemplateResult
            : undefined;

        const select2Instance = _this.select2({
          minimumResultsForSearch,
          tags,
          templateSelection,
          templateResult
        });

        if (_this.hasClass('select-resolve-width')) {
          select2Instance.on('select2:unselecting', function(e){
            // before removing tag we check option element of tag and
            // if it has property 'locked' we will create error to prevent all select2 functionality
            if ($(e.params.args.data.element).attr('locked')) {
              e.select2.pleaseStop();
            }
          });
        }
      });
    }
  });
};

export default selects;
