(function ($, Drupal) {

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

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

    /**
     * Initialise "audio" trait using the media trait defaults
     */
    editor.PDMediaManager.addTrait('audio', '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 audio') + '"></button>');
          $btnRemove.click(function () {
            if (confirm(Drupal.t('Remove audio from component?'))) {
              trait.model.set('value', { id: null });
              trait.getMetaData()
            }
          });
          $metaContainer.append($btnRemove);
        }
        return $metaContainer[0];
      }
    });

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

                  // 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_audio_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-audio"></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('audio/')) {
              return {
                type: 'audio',
                src: ''
              };
            }
            if (typeof value.bundle == 'string' && value.bundle == 'audio') {
              value.type = value.bundle;
              return value;
            }
          }
        },
      },
    );
    editor.AssetManager.getType('audio').upload = function (file) {
      var reader = new FileReader();
      var promise = jQuery.Deferred();
      reader.onload = function () {
        Drupal.restconsumer.upload(
          '/file/upload/media/audio/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/audio' } },
              "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.audio.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);
