(function ($, Drupal) {
  var AssetManager = null;
  function init(editor) {
    AssetManager = editor.AssetManager;

    AssetManager.add([]);
    AssetManager.render();
    $('.gjs-am-file-uploader').before('<div id="pd-asset-edit"></div>');
    var imageAsset = AssetManager.getType('image');
    AssetManager.mediaAsset =
    {
      view:
        imageAsset.view.extend
          (
            {
              init(o) {
                const pfx = this.pfx;
                this.className += ` ${pfx}asset-` + this.model.get('type');

                // highlight selected item
                if (this.collection.target && this.collection.target.model && this.collection.target.model.getTargetValue().id == this.model.attributes.id) {
                  this.className += ` ${pfx}highlight`;
                  this.onClick();
                }
              },
              getInfo() {
                const pfx = this.pfx;
                const model = this.model;
                let name = model.get('name');
                let size = Math.round(model.get('size') / 10) / 100;
                if (size > 1000) {
                  size = Math.round(size / 1000);
                  size += " MB";
                } else {
                  size += " KB";
                }
                name = name || model.getFilename();
                return `
                      <div class="${pfx}name">${name}</div>
                      <div class="${pfx}size">${size}</div>
                    `;
              },
              updateTarget(trait) {
                trait.setValueFromAssetManager({
                  id: this.model.get('id'),
                  src: this.model.get('src'),
                  title: this.model.get('name')
                });
              },
              onClick() {
                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();
                });
                $('.pd-asset-form').on('submit', 'form', function (e) {
                  e.preventDefault();
                  Drupal.restconsumer.submit($(this), { 'op': 'Save' }).done(function () {
                    $('.gjs-am-assets-header form .form-actions .form-submit').click();
                  });
                  $('.pd-asset-form').remove();
                })
              },
              onDblClick() {
                const { em, model } = this;
                $('.pd-asset-form').remove();
                this.updateTarget(this.collection.target);
                em && em.get('Modal').close();
              },
              getPreview() {
                return `<div class="gjs-am-preview fas fa-file"></div>`;
              },
            }
          ),
      isType: function (value) {
        if (typeof value == 'object') {
          if (typeof value.bundle == 'string') {
            value.type = value.bundle;
            return value;
          }
        } else {
          return null
        }
      },
      upload: function (file) {
        var reader = new FileReader();
        var type = this.id;
        var field = this.field;
        reader.onload = function () {
          Drupal.restconsumer.upload(
            '/file/upload/media/' + type + '/' + field,
            file.name,
            reader.result
          )
            .done(function (result) {
              result = JSON.parse(result);
              var mediaData =
              {
                "_links": { "type": { "href": window.location.protocol + '//' + window.location.hostname + '/rest/type/media/' + type } },
                "name": [{ "value": file.name }]
              };
              if (drupalSettings.pagedesigner.media[type].translatable) {
                mediaData.langcode = [{ "value": drupalSettings.path.currentLanguage }];
              }
              mediaData[field] = [{ "target_id": result.fid[0].value, 'alt': result.filename[0].value }];
              Drupal.restconsumer.post('/entity/media', mediaData).done(function () {
                $('.gjs-am-assets-header form .form-actions .form-submit').click();
              });
            }
            );
        }
        reader.readAsArrayBuffer(file);
      }
    };

    editor.on('run:open-assets',
      (something, config) => {
        if (config.accept == '*') {
          initAssets();
        }
      }
    );

    function initAssets() {
      if ($('.gjs-am-assets-header .gjs-am-add-asset').length == 0) {
        $('.gjs-am-assets-header').empty().append('<div class="gjs-am-add-asset"></div>');
      }
      Drupal.ajax
        (
          {
            url: '/pagedesigner/form/asset/search/media'
          }
        )
        .execute()
        .then(
          function (data) {
            setTimeout(() => editor.PDMediaManager.processForm('*'), 500);
          }
        );

    }
  }

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

})(jQuery, Drupal);
