(function ($, Drupal) {

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

  function init(editor) {
    const TraitManager = editor.TraitManager;
    TraitManager.addType('target',
      Object.assign({}, TraitManager.defaultTrait,
        {
          events: {
            change: 'onChange', // trigger parent onChange method on keyup
          },

          afterInit: function () {


            var value = '_top';

            if (typeof this.model.attributes.additional.preview !== 'undefined' && this.model.attributes.additional.preview) {
              value = this.model.attributes.additional.preview;
            }

            if (this.model.get('value') && this.model.get('value')[0] && ['_top', '_blank'].indexOf(this.model.get('value')[0]) > -1) {
              value = this.model.get('value')[0];
            } else {
              this.model.set('value', [value]);
              editor.getSelected().set('changed', false);
            }

            $(this.inputEl).find('option[value="' + value + '"]').attr('selected', 'selected');
          },

          getInputEl: function () {
            if (!this.inputEl) {
              var select = $('<select>');
              select.append('<option value="_top">' + Drupal.t('Same window') + '</option>');
              select.append('<option value="_blank">' + Drupal.t('New window') + '</option>');
              this.inputEl = select.get(0);
            }
            return this.inputEl;
          },
          getRenderValue: function (value) {
            if (typeof this.model.get('value') == 'undefined') {
              return value;
            }
            return this.model.get('value');
          },
          setTargetValue: function (value) {
            this.model.set('value', value);
          },
          setInputValue: function (value) {
            if (value) {
              $(this.inputEl).val(value);
            }
            this.model.set('value', value);
          }
        })
    );
  }

})(jQuery, Drupal);
