(function ($, Drupal) {

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

  /**
   * Intitialize trait and asset "embed"
   *
   * @param {Object} editor The grapes editor
   */
  function init(editor) {

    /**
     * Initialise "embed" trait using the media trait defaults
     */
    editor.PDMediaManager.addTrait('embed', 'text', {
      getMetaData: function getMetaData() {
        if (!this.$metaHolder.hasClass('btn-remove')) {
          var trait = this;
          this.$metaHolder.attr('title', Drupal.t('Remove embed'));
          this.$metaHolder.click(function () {
            if (confirm(Drupal.t('Remove embed file from component?'))) {
              trait.model.set('value', { id: null });
              trait.getMetaData()
            }
          });
          this.$metaHolder.addClass('btn-remove');
        }
        if (this.model.get('value') && this.model.get('value').src) {
          if (this.model.get('value').src.indexOf('youtube') !== -1) {
            return '<img src="https://img.youtube.com/vi/' + this.model.get('value').src.split('/').pop() + '/0.jpg"/>';
          }
        }
        return '';
      }
    });

    editor.AssetManager.add([]);
    editor.AssetManager.render();
    $('.gjs-am-file-uploader').before('<div id="pd-asset-edit"></div>');
    // Overwrite image asset type to provide value to trait
    var imageAsset = editor.AssetManager.getType('image');
    editor.AssetManager.addType(
      'embed',
      {
        view:
          imageAsset.view.extend
            (
              {
                init(o) {
                  const pfx = this.pfx;
                  this.className += ` ${pfx}asset-embed`;
                  selection = [];

                  // highlight selected item
                  if (this.collection.target && this.collection.target.model && this.collection.target.model.getTargetValue() && this.collection.target.model.getTargetValue().id == this.model.attributes.id) {
                    this.className += ` ${pfx}highlight`;
                    this.onClick();
                  }
                },
                getPreview() {
                  const pfx = this.pfx;
                  var preview = this.model.get('preview');
                  return `
                  <div class="${pfx}preview" style="background-image: url('${preview}');"></div>
                  <div class="${pfx}preview-bg ${this.ppfx}checker-bg"></div>
                `;
                },
                getInfo() {
                  const pfx = this.pfx;
                  const model = this.model;
                  let name = model.get('name');
                  let provider = model.get('provider');
                  return `
                      <div class="${pfx}name">${name}</div>
                      <div class="${pfx}provider">${provider}</div>
                    `;
                },
                updateTarget(trait) {
                  if (trait.setValueFromAssetManager) {
                    trait.setValueFromAssetManager({
                      id: this.model.get('id'),
                      src: this.model.get('src'),
                      title: this.model.get('name'),
                      preview: this.model.get('preview')
                    });
                  }
                },
                onClick() {
                  if (!this.$el.hasClass(this.pfx + 'highlight')) {

                    this.collection.trigger('deselectAll');
                    this.$el.addClass(this.pfx + 'highlight');

                    var id = this.model.attributes.id;
                    if ($('.pd-asset-form').length == 0) {
                      $('.gjs-am-file-uploader').prepend('<div class="pd-asset-form"></div>');
                    }
                    $('.pd-asset-form').empty();
                    if ($('#pd-asset-edit').length == 0) {
                      $('.pd-asset-form').append('<div id="pd-asset-edit"></div>');
                    }

                    Drupal.ajax({ url: '/media/' + id + '/edit', wrapper: 'pd-asset-edit' }).execute().then(function () {
                      if ($('.pd-asset-form .form-actions').find('input[type="reset"]').length == 0) {
                        var cancelButton = $('<input type="reset" value="' + Drupal.t('Cancel edit') + '" class="button button--primary js-form-submit form-submit">');
                        cancelButton.on('click', function () {
                          $('.pd-asset-form').remove();
                        });
                        $('.pd-asset-form .form-actions').append(cancelButton);
                      }
                      $('.pd-asset-form input[name=field_media_image_0_remove_button], .pd-asset-form .form-type-vertical-tabs, .pd-asset-form .button--danger').hide();
                    });
                  }
                },
                onDblClick() {
                  const { em, model } = this;
                  $('.pd-asset-form').remove();
                  this.updateTarget(this.collection.target);
                  em && em.get('Modal').close();
                },
                onRemove(e) {
                  const model = this.model
                  e.stopImmediatePropagation();
                  if (confirm(Drupal.t('Do you really want to delete "%file"?\nIt might be used on other pages.').replace('%file', model.get('name')))) {
                    this.model.collection.remove(this.model);
                    editor.PDMediaManager.delete(model.get('id'));
                  }
                }
              }
            ),
        isType: function (value) {
          if (typeof value == 'object') {
            if (typeof value.type == 'string' && value.type.startsWith('embed/')) {
              return {
                type: 'embed',
                src: ''
              };
            }
            if (typeof value.bundle == 'string' && value.bundle == 'embed') {
              value.type = value.bundle;
              return value;
            }
            if (typeof value.type == 'string' && value.type == 'text/uri-list') {
              return {
                type: 'embed',
                src: ''
              };
            }
          }
        },
        upload: function (links) {
          links.split(/\n/).forEach(function (link) {
            var mediaData =
            {
              "_links": { "type": { "href": window.location.protocol + '//' + window.location.hostname + '/rest/type/media/embed' } },
              "field_embed_source": [{ "value": link }],
              "name": [{ "value": link }],
            };
            if (drupalSettings.pagedesigner.media.embed.translatable) {
              mediaData.langcode = [{ "value": drupalSettings.path.currentLanguage }];
            }
            Drupal.restconsumer.post('/entity/media', mediaData).done(function () {
              $('.gjs-am-assets-header form .form-actions .form-submit').click();
            });
          });
        }
      },
    );
  }

})(jQuery, Drupal);
