(function ($, Drupal) {

  Drupal.behaviors.pagedesigner_image_editor_before_setup = {
    attach: function (context, settings) {
      once('pagedesigner_image_editor_before_setup', 'body', context).forEach(() => {
        $(document).on('pagedesigner-before-setup', function (e) {

          grapes_plugins.push('grapesjs-tui-image-editor');

          grapes_plugin_options['grapesjs-tui-image-editor'] = {
            config: {
              includeUI: {
                menu: ['crop', 'flip', 'rotate', 'filter'],
                initMenu: 'crop',
                menuBarPosition: 'right'
              },
            },
            height: '900px',
            labelApply: 'Save changes',
            labelImageEditor: 'Image Editor',

            onApply: (imageEditor, imageModel) => {
              const dataUrl = imageEditor.toDataURL();
              var reader = new FileReader();
              var trait = imageModel;

              var d = new Date();
              var date_str = d.toISOString().substr(0, 19).replace(/[^\d]/g, '')
              var file_parts = imageEditor.ui.initializeImgUrl.split('/').pop().split('.');
              var file_ext = file_parts.pop();
              var file_name = file_parts.join('.') + '-edit' + date_str + '.' + file_ext;

              reader.onload = function () {
                Drupal.restconsumer.upload(
                  '/file/upload/media/image/field_media_image',
                  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/image' } },
                    "field_media_image": [{ "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.image.translatable) {
                    mediaData.langcode = [{ "value": drupalSettings.path.currentLanguage }];
                  }
                  Drupal.restconsumer.post('/entity/media', mediaData).done(function (response) {

                    // if is image trait, store id
                    // otherweise, set background image
                    if (trait.setValueFromAssetManager) {
                      if (!trait.isMultiSelect) {
                        trait.setValueFromAssetManager({
                          id: response.vid[0].value,
                          src: response._embedded[Object.keys(response._embedded)[2]][0]._links.self.href,
                          alt: '',
                          preview: response._embedded[Object.keys(response._embedded)[1]][0]._links.self.href,
                        });
                      }
                    } else {
                      // seems hacky
                      var styles = trait.getStyle();
                      styles['background-image'] = 'url(' + response._embedded[Object.keys(response._embedded)[2]][0]._links.self.href.replace(location.origin, '') + ')';
                      trait.setStyle(styles);
                    }

                    editor.Modal.close();
                    editor.PDMediaManager.loadForm(trait, 'image');
                  });
                });
              }
              reader.readAsArrayBuffer(editor.Commands.get('tui-image-editor').dataUrlToBlob(dataUrl));
            },

            icons: {
              'menu.normalIcon.path': '/modules/contrib/pagedesigner/modules/pagedesigner_imageedit/resources/img/icon-d.svg',
              'menu.activeIcon.path': '/modules/contrib/pagedesigner/modules/pagedesigner_imageedit/resources/img/icon-b.svg',
              'menu.disabledIcon.path': '/modules/contrib/pagedesigner/modules/pagedesigner_imageedit/resources/img/icon-a.svg',
              'menu.hoverIcon.path': '/modules/contrib/pagedesigner/modules/pagedesigner_imageedit/resources/img/icon-c.svg',
              'submenu.normalIcon.path': '/modules/contrib/pagedesigner/modules/pagedesigner_imageedit/resources/img/icon-d.svg',
              'submenu.activeIcon.path': '/modules/contrib/pagedesigner/modules/pagedesigner_imageedit/resources/img/icon-c.svg',
            },
          };
        });
      });
    }
  };

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

          // extend image asset
          var imageAsset = editor.AssetManager.getType('image');
          editor.AssetManager.addType(
            'image', {
            view: imageAsset.view.extend({
              events: {
                'click [data-toggle=asset-remove]': 'onRemove',
                'click [data-toggle=edit-image]': 'onOpenEditor',
                click: 'onClick',
                dblclick: 'onDblClick'
              },

              template() {
                const pfx = this.pfx;
                return `
                  <div class="${pfx}preview-cont">
                    ${this.getPreview()}
                  </div>
                  <div class="${pfx}meta">
                    ${this.getInfo()}
                  </div>
                  <div class="${pfx}close" data-toggle="asset-remove">
                    &Cross;
                  </div>
                  <a data-toggle="edit-image" class="btn-edit" ><i class="fas fa-pencil-alt"></i></a>
                `;
              },

              onOpenEditor(e) {
                this.model.trait = this.collection.target;
                editor.runCommand('tui-image-editor', {
                  target: this.model.trait,
                  image: this.model.get('src')
                });
              }
            }),
          },
          );
        });
      });
    }
  };

})(jQuery, Drupal);
