(function ($, Drupal) {

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

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

    /**
     * Initialise "document" trait using the media trait defaults
     */
    editor.PDMediaManager.addTrait('document', 'file', {
      getMetaData: function getMetaData() {
        var $metaContainer = $('<div></div>');

        if (this.model.get('value') && this.model.get('value').src) {
          $metaContainer.append('<a href="' + this.model.get('value').src + '" target="_blank">' + this.model.get('value').src.split('/').pop() + '</a>');
          var trait = this;
          var $btnRemove = $('<button title="' + Drupal.t('Remove document') + '"></button>');
          $btnRemove.click(function () {
            if (confirm(Drupal.t('Remove document from component?'))) {
              trait.model.set('value', { id: null });
              trait.getMetaData()
            }
          });
          $metaContainer.append($btnRemove);
        }
        return $metaContainer[0];
      }
    });

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

                  // 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() {
                  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();
                },
                getPreview() {
                  return `<div class="gjs-am-preview fas fa-file"></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('application/') || value.type.startsWith('text/'))) {
              return {
                type: 'document',
                src: ''
              };
            }
            if (typeof value.bundle == 'string' && value.bundle == 'document') {
              value.type = value.bundle;
              return value;
            }
          } else {

          }
        },
      },
    );
    am.getType('document').upload = function (file) {
      var reader = new FileReader();
      var promise = jQuery.Deferred();
      reader.onload = function () {
        Drupal.restconsumer.upload(
          '/file/upload/media/document/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/document' } },
              "field_media_file": [{ "target_id": result.fid[0].value, 'alt': result.filename[0].value }],
              "name": [{ "value": file.name }],
              "uid": [{ "target_id": drupalSettings.user.uid }],
            };
            if (drupalSettings.pagedesigner.media.document.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;
    }
  }

})(jQuery, Drupal);
