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

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

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

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

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

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

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

      this.listenTo(buttonView, 'execute', () => {
        this._openDialog(
          dialogURL,
          ({ settings }) => {
            editor.execute('insertMapEmbed', settings);
          },
          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;
  }
}
