(function ($, Drupal, drupalSettings) {

  var selected = false;
  function init(editor) {
    const TraitManager = editor.TraitManager;
    TraitManager.addType('link',
      Object.assign({}, TraitManager.defaultTrait,
        {
          events: {},

          afterInit: function () {
            var linktrait = this;

            var action = jQuery(this.inputEl);
            var input = action.find('input');
            input.on('autocompleteselect', function (event, entry) {
              var value = {
                uri: entry.item.path,
                title: entry.item.value
              };
              input.val(value.uri);
              linktrait.setTargetValue(value);
              linktrait.getMetaData();
              input.blur();
              selected = true;
              event.preventDefault();
            });
            Drupal.behaviors.linkit_autocomplete.attach(action[0]);

          },
          getMetaData: function () {
            var value = this.model.get('value');
            if ( value && value.uri ) {
              var $metaContainer = $('<div></div>');
              value.title = value.title || value.uri;
              if (value.title && value.title.length > 255) {
                value.title = `${value.title.slice(0, 254)}…`;
              }
              $metaContainer.append('<a href="' + value.uri + '" target="_blank">' + value.title + '</a>');
              var trait = this;
              var $btnRemove = $('<button title="' + Drupal.t('Remove link') + '"></button>');
              $btnRemove.click(function(){
                if (confirm(Drupal.t('Remove link from component?'))) {
                  trait.model.set('value',  {uri: null});
                  $(trait.inputEl).find('input').val('');
                  trait.getMetaData();
                }
              });
              $metaContainer.append($btnRemove);
              return $metaContainer[0];
            }
            return '';
          },
          getInputEl: function () {
            if (!this.inputEl) {
              var action = jQuery('<div />');
              var trait = this;
              if (drupalSettings.link_autocomplete) {
                var input = jQuery('<input type="text" name="link" class="form-linkit-autocomplete ui-autocomplete-input" data-autocomplete-path="/linkit/autocomplete/default_linkit" style="width:100%" maxlength="2048" autocomplete="off" />');
              }
              else {
                var input = jQuery('<input type="text" name="link" style="width:100%" maxlength="2048" />');
              }

              input.blur(function(){
                if( $(this).val() ){
                  if( trait.model.get('value') && !trait.model.get('value').uri ){
                    var link = $(this).val();
                    link = ((link.indexOf('://') === -1) && (link.indexOf('mailto:') === -1) && (link.charAt(0) != '#') ) ? 'http://' + link : link;
                    trait.model.set('value',  {uri:  link});
                    trait.getMetaData();
                  }
                }else{
                  trait.model.set('value',  {uri: null});
                  trait.getMetaData();
                }
              });

              action.append(input);
              var value = this.model.get('value');
              if (value && value.uri != null) {
                input.val(value.uri);
              }
              this.inputEl = action.get(0);
            }
            return this.inputEl;
          },
          getRenderValue: function (value) {
            if( value && typeof value != 'undefined' ){
              return this.model.get('value').uri;
            }else{
              return value;
            }
          },
          setTargetValue: function (value) {
            this.model.set('value', value);
          },
          setInputValue: function (value) {
            if (value && value.uri != null) {
              $(this.inputEl).find('input').val(value.uri);
            }
            this.model.set('value', value);
          }
        })
    );
  }

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

})(jQuery, Drupal, drupalSettings);
