/**
 * @file
 * JavaScript behaviors for HTML editor integration.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  // @see http://docs.ckeditor.com/#!/api/CKEDITOR.config
  Drupal.webform = Drupal.webform || {};
  Drupal.webform.htmlEditor = Drupal.webform.htmlEditor || {};
  Drupal.webform.htmlEditor.options = Drupal.webform.htmlEditor.options || {};

  /**
   * Initialize HTML Editor.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformHtmlEditor = {
    attach: function (context) {
      if (!window.CKEDITOR) {
        return;
      }

      $(context).find('textarea.js-html-editor').once('webform-html-editor').each(function () {
        var $textarea = $(this);

        var allowedContent = drupalSettings['webform']['html_editor']['allowedContent'];

        // Load additional CKEditor plugins used by the Webform HTML editor.
        // @see \Drupal\webform\Element\WebformHtmlEditor::preRenderWebformHtmlEditor
        // @see \Drupal\webform\WebformLibrariesManager::initLibraries
        var plugins = drupalSettings['webform']['html_editor']['plugins'];

        // If requirejs is present don't use the codemirror plugin.
        // @see Issue #2936147: ckeditor.codemirror plugin breaks admin textarea.
        // @todo Remove the below code once this issue is resolved.
        if (plugins.codemirror
          && drupalSettings.yamlEditor
          && drupalSettings.yamlEditor.source
          && drupalSettings.yamlEditor.source.indexOf('noconflict') !== -1) {
          delete plugins.codemirror;
          if ('console' in window) {
            window.console.log('YAML Editor module is not compatible with the ckeditor.codemirror plugin. @see Issue #2936147: ckeditor.codemirror plugin breaks admin textarea.');
          }
        }

        for (var plugin_name in plugins) {
          if (plugins.hasOwnProperty(plugin_name)) {
            CKEDITOR.plugins.addExternal(plugin_name, plugins[plugin_name]);
          }
        }

        var options = {
          // Turn off external config and styles.
          customConfig: '',
          stylesSet: false,
          contentsCss: [],
          allowedContent: allowedContent,
          // Use <br> tags instead of <p> tags.
          enterMode: CKEDITOR.ENTER_BR,
          shiftEnterMode: CKEDITOR.ENTER_BR,
          // Set height.
          height: '100px',
          // Remove status bar.
          resize_enabled: false,
          removePlugins: 'elementspath,magicline',
          // Toolbar settings.
          format_tags: 'p;h2;h3;h4;h5;h6',
          // extraPlugins
          extraPlugins: ''
        };

        // Add toolbar.
        if (!options.toolbar) {
          options.toolbar = [];
          options.toolbar.push({name: 'styles', items: ['Format', 'Font', 'FontSize']});
          options.toolbar.push({name: 'basicstyles', items: ['Bold', 'Italic', 'Subscript', 'Superscript']});
          // Add IMCE image button.
          if (CKEDITOR.plugins.get('imce')) {
            CKEDITOR.config.ImceImageIcon = drupalSettings['webform']['html_editor']['ImceImageIcon'];
            options.extraPlugins += (options.extraPlugins ? ',' : '') + 'imce';
            options.toolbar.push({name: 'insert', items: ['ImceImage', 'SpecialChar']});
          }
          else {
            options.toolbar.push({name: 'insert', items: ['SpecialChar']});
          }

          // Add link plugin.
          if (plugins['link']) {
            options.extraPlugins += (options.extraPlugins ? ',' : '') + 'link';
            options.toolbar.push({name: 'links', items: ['Link', 'Unlink']});
          }
          options.toolbar.push({name: 'colors', items: ['TextColor', 'BGColor']});
          options.toolbar.push({name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote']});
          options.toolbar.push({name: 'tools', items: ['Source', '-', 'Maximize']});
        }

        // Add autogrow plugin.
        if (plugins['autogrow']) {
          options.extraPlugins += (options.extraPlugins ? ',' : '') + 'autogrow';
          options.autoGrow_minHeight = 60;
          options.autoGrow_maxHeight = 300;
        }

        // Add CodeMirror integration plugin.
        if (plugins['codemirror']) {
          options.extraPlugins += (options.extraPlugins ? ',' : '') + 'codemirror';
          options.codemirror = {
            mode: 'text/html'
          };
        }

        options = $.extend(options, Drupal.webform.htmlEditor.options);

        // Catch and suppress
        // "Uncaught TypeError: Cannot read property 'getEditor' of undefined".
        //
        // Steps to reproduce this error.
        // - Goto any form elements.
        // - Edit an element.
        // - Save the element.
        try {
          CKEDITOR.replace(this.id, options).on('change', function (evt) {
            // Save data onchange since Ajax dialogs don't execute form.onsubmit.
            $textarea.val(evt.editor.getData().trim());
          });
        }
        catch (e) {
          // Do nothing.
        }
      });
    }
  };

})(jQuery, Drupal, drupalSettings);
