import { Plugin } from 'ckeditor5/src/core';
import { ButtonView } from 'ckeditor5/src/ui';

import mediaIcon from './../theme/icons/map_icon.svg';

export default class MapEmbedUi extends Plugin {
  init() {
    const editor = this.editor;
    const options = editor.config.get('simpleInteractiveMaps');

    if (!options) {
      return;
    }

    const { dialogUrl, openDialog, dialogSettings = {} } = options;

    if (!dialogUrl || typeof openDialog !== 'function') {
      return;
    }

    editor.ui.componentFactory.add('simpleInteractiveMap', (locale) => {
      const command = editor.commands.get('insertMapEmbed');
      const buttonView = new ButtonView(locale);

      buttonView.set( {
        label: editor.t('Insert Simple Interactive Map'),
        icon: mediaIcon,
        tooltip: true,
      });

      buttonView.bind('isOn', 'isEnabled').to(command, 'value', 'isEnabled');

      this.listenTo(buttonView, 'execute', () => {
        this._openDialog(
          libraryUrl,
          ({attributes}) => {
            editor.execute('insertMapEmbed', attributes);
          },
          dialogSettings,
        );
      });

      return buttonView;
    });
  }

  _openDialog(url, callback, settings) {
    const ckeditorAjaxDialog = Drupal.ajax({
      dialog: settings,
      dialogType: 'modal',
      selector: '.ckeditor5-dialog-loading-link',
      url: url,
      progress: {
        type: 'fullscreen',
        message: 'Please wait...',
      },
    });
    ckeditorAjaxDialog.execute();

    Drupal.ckeditor5.saveCallback = callback;
  }
}
