(function ($, Drupal, drupalSettings) {

  var selected = false;
  function init(editor) {
    const TraitManager = editor.TraitManager;
    TraitManager.addType('autocomplete',
      Object.assign({}, TraitManager.defaultTrait,
        {
          events: {},
          afterInit: function () {
            var trait = this;
            var autocomplete = this;
            var input = $(this.getInputEl()).find('input');
            input.on('autocompleteselect', function (event, entry) {
              if (!entry.item.value) {
                return;
              }
              var value = autocomplete.getRenderValue();
              if (typeof value == 'undefined') {
                value = [];
              }
              if (trait.model.attributes.additional.additional.multiple) {
                value.push({
                  label: entry.item.label,
                  value: entry.item.value,
                  id: Number.parseInt(entry.item.value.match(/\(([0-9]+)\)$/)[1])
                });
              } else {
                value = [{
                  label: entry.item.label,
                  value: entry.item.value,
                  id: Number.parseInt(entry.item.value.match(/\(([0-9]+)\)$/)[1])
                }];
                input.val(value.value);
              }
              autocomplete.setTargetValue(value);
              input.blur();
              selected = true;
              event.preventDefault();
            });
            Drupal.behaviors.autocomplete.attach($(this.getInputEl()).get(0));
          },
          getInputEl: function () {
            if (!this.inputEl) {
              var container = $('<div />');
              var trait = this;
              var input = $('<input type="text" name="autocomplete" class="form-autocomplete ui-autocomplete-input" style="width:100%" maxlength="2048" autocomplete="off" />');
              input.attr('data-autocomplete-path', this.model.attributes.additional.additional.autocomplete_href);
              input.blur(function () {
                setTimeout(function () {
                  if (input.get(0) === document.activeElement) {
                    return;
                  }
                  var value = trait.model.get('value', value);
                  if (input.val()) {
                    if (value) {
                      var ids = Drupal.autocomplete.splitValues(input.val()).map(
                        function (e) {
                          var match = e.match(/\((\d+)\)/);
                          if (Array.isArray(match)) {
                            return Number.parseInt(match[1]);
                          }
                          return null;
                        }
                      );
                      ids.filter(n => n);
                      value = value.map(
                        function (v, i, value) {
                          if (v == null || ids.includes(v.id)) {
                            return v;
                          } else {
                            return null;
                          }
                        }
                      );
                      value.filter(n => n);
                      trait.model.set('value', value);
                    }
                  } else {
                    trait.model.set('value', []);
                  }
                }, 100);
              });
              container.append(input);
              var value = this.model.get('value');
              var inputValue = [];
              for (var x in value) {
                inputValue.push(value[x].value);
              }
              input.val(inputValue.join(', '));
              this.inputEl = container.get(0);
            }
            return this.inputEl;
          },
          getRenderValue: function (value) {
            return this.model.get('value');
          },
          setTargetValue: function (value) {
            this.model.set('value', value);
          },
          setInputValue: function (value) {
            if (Array.isArray(value) && value.length > 0) {
              var inputValue = [];
              for (var x in value) {
                inputValue.push(value[x].value);
              }
              $(this.getInputEl()).find('input').val(inputValue.join(', '));
              this.model.set('value', value);
            }
          }
        })
    );
  }

  Drupal.behaviors.pagedesigner_autocomplete = {
    attach: function (context, settings) {
      $(document).on('pagedesigner-init-traits', function (e, editor) {
        init(editor);
      });
    }
  };

})(jQuery, Drupal, drupalSettings);
