(function ($, Drupal) {

  function init(editor) {
    editor.PDMediaManager.addTrait('svg', 'file', {
      getMetaData: function getMetaData() {
        if (!this.$metaHolder.hasClass('btn-remove')) {
          var trait = this;
          this.$metaHolder.attr('title', Drupal.t('Remove SVG file'));
          this.$metaHolder.click(function () {
            if (confirm(Drupal.t('Remove SVG 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) {
          return '<img src="' + this.model.get('value').src + '"/>';
        }
        return '';
      }
    });

    var am = editor.AssetManager;
    am.add([]);
    am.render();
    $('.gjs-am-file-uploader').before('<div id="pd-asset-edit"></div>');

    // Overwrite image asset type to provide value to trait
    var imageAsset = am.getType('image');
    am.addType(
      'svg',
      {
        view:
          imageAsset.view.extend
            (
              {
                init(o) {
                  const pfx = this.pfx;
                  this.className += ` ${pfx}asset-svg`;

                  // 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();
                  }
                },
                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_svg_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();
                },
                getPreview() {
                  const pfx = this.pfx;
                  const preview = this.model.get('src');
                  return `
                    <div class="${pfx}preview" ><img src="${preview}"/></div>
                    <div class="${pfx}preview-bg ${this.ppfx}checker-bg"></div>
                    `;
                },
                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('image/svg')) {
              return {
                type: 'svg',
                src: ''
              };
            }
            if (typeof value.bundle == 'string' && value.bundle == 'svg') {
              value.type = value.bundle;
              return value;
            }
          }
        },
      },
    );
    am.getType('svg').upload = function (file) {
      var reader = new FileReader();
      var promise = jQuery.Deferred();
      reader.onload = function () {
        Drupal.restconsumer.upload(
          '/file/upload/media/svg/field_media_file',
          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/svg' } },
              "field_media_file": [{ "target_id": result.fid[0].value, 'alt': file.name }],
              "name": [{ "value": file.name }],
              "uid": [{ "target_id": drupalSettings.user.uid }],
            };
            if (drupalSettings.pagedesigner.media.svg.translatable) {
              mediaData.langcode = [{ "value": drupalSettings.path.currentLanguage }];
            }
            Drupal.restconsumer.post('/entity/media', mediaData).done(function () {
              promise.resolve();
            }).fail(function () {
              promise.reject();
            });
          }).fail(function () {
            promise.reject();
          });
      }
      reader.readAsArrayBuffer(file);
      return promise;
    }
  }

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

})(jQuery, Drupal);
