(function ($, Drupal) {

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

          afterInit: function () {

            var value = Object.keys(this.options)[0];

            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] && Object.keys(this.options).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 options = this.model.attributes.additional.options;
              this.options = options;

              // Sort the options
              var keys = Object.keys(options).sort(function (a,b) {
                if (options[a] <options[b]) {return -1;}
                if (options[a] > options[b]) {return 1;}
                return 0;
              });

              var select = $('<select>');
              for (var key in keys) {
                var option = $('<option value="' + keys[key] + '">' + this.options[keys[key]] + '</option>');
                select.append(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.model.set('value', value);
              $(this.inputEl).val(value);
            }
          }
        })
    );
  }

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

})(jQuery, Drupal);
