/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */
if (!CKEDITOR.plugins.get('videoembed')) {
  var REGEX_HTTP = /^https?/;
  CKEDITOR.DEFAULT_LFR_EMBED_WIDGET_TPL = '<div data-embed-url="{url}" class="embed-responsive embed-responsive-16by9">{content}<div class="embed-help-message">{helpMessageIcon}<span> {helpMessage}</span></div></div><br>';
  /**
   * Enum for supported embed alignments
   * @type {Object}
   */

  var EMBED_ALIGNMENT = {
    CENTER: 'center',
    LEFT: 'left',
    RIGHT: 'right'
  };
  /**
   * Enum values for supported embed alignments
   * @type {Array}
   */

  var ALIGN_VALUES = [EMBED_ALIGNMENT.CENTER, EMBED_ALIGNMENT.LEFT, EMBED_ALIGNMENT.RIGHT];
  /**
   * Necessary styles for the center alignment
   * @type {Array.<Object>}
   */

  var CENTERED_EMBED_STYLE = [{
    name: 'display',
    value: 'block'
  }, {
    name: 'margin-left',
    value: 'auto'
  }, {
    name: 'margin-right',
    value: 'auto'
  }];
  /**
   * Retrieves the alignment value of an embed element.
   *
   * @param {CKEDITOR.dom.element} embed The embed element
   * @return {String} The alignment value
   */

  var getEmbedAlignment = function getEmbedAlignment(embed) {
    var embedAlignment = embed.getStyle('float');

    if (!embedAlignment || embedAlignment === 'inherit' || embedAlignment === 'none') {
      embedAlignment = embed.getAttribute('align');
    }

    if (!embedAlignment) {
      var centeredEmbed = CENTERED_EMBED_STYLE.every(function (style) {
        var styleCheck = embed.getStyle(style.name) === style.value;

        if (!styleCheck && style.vendorPrefixes) {
          styleCheck = style.vendorPrefixes.some(function (vendorPrefix) {
            return embed.getStyle(vendorPrefix + style.name) === style.value;
          });
        }

        return styleCheck;
      });
      embedAlignment = centeredEmbed ? EMBED_ALIGNMENT.CENTER : null;
    }

    return embedAlignment;
  };
  /**
   * Removes the alignment value of an embed
   *
   * @param {CKEDITOR.dom.element} embed The embed element
   * @param {String} embedAlignment The embed alignment value to be removed
   */


  var removeEmbedAlignment = function removeEmbedAlignment(embed, embedAlignment) {
    if (embedAlignment === EMBED_ALIGNMENT.LEFT || embedAlignment === EMBED_ALIGNMENT.RIGHT) {
      embed.removeStyle('float');

      if (embedAlignment === getEmbedAlignment(embed)) {
        embed.removeAttribute('align');
      }
    } else if (embedAlignment === EMBED_ALIGNMENT.CENTER) {
      CENTERED_EMBED_STYLE.forEach(function (style) {
        embed.removeStyle(style.name);

        if (style.vendorPrefixes) {
          style.vendorPrefixes.forEach(function (vendorPrefix) {
            return embed.removeStyle(vendorPrefix + style.name);
          });
        }
      });
    }
  };
  /**
   * Sets the alignment value of an embed
   *
   * @param {CKEDITOR.dom.element} embed The embed element
   * @param {String} embedAlignment The embed alignment value to be set
   */


  var setEmbedAlignment = function setEmbedAlignment(embed, embedAlignment) {
    removeEmbedAlignment(embed, getEmbedAlignment(embed));

    if (embedAlignment === EMBED_ALIGNMENT.LEFT || embedAlignment === EMBED_ALIGNMENT.RIGHT) {
      embed.setStyle('float', embedAlignment);
    } else if (embedAlignment === EMBED_ALIGNMENT.CENTER) {
      CENTERED_EMBED_STYLE.forEach(function (style) {
        embed.setStyle(style.name, style.value);

        if (style.vendorPrefixes) {
          style.vendorPrefixes.forEach(function (vendorPrefix) {
            return embed.setStyle(vendorPrefix + style.name, style.value);
          });
        }
      });
    }
  };

  var getSelectedElement = function getSelectedElement(editor) {
    var result = {
      alignment: null,
      element: null
    };
    var selection = editor.getSelection();

    if (selection) {
      var selectedElement = selection.getSelectedElement();

      if (selectedElement && selectedElement.getAttribute('data-cke-widget-wrapper')) {
        result.alignment = getEmbedAlignment(selectedElement);
        result.element = selectedElement;
      }
    }

    return result;
  };

  var resizeElement = function resizeElement(el, width, height) {
    var wrapperElement = el.parentElement;

    if (wrapperElement && width > 0 && height > 0) {
      wrapperElement.setAttribute('style', "width:".concat(width, "px;"));
      var widgetElement = wrapperElement.querySelector('[data-widget="videoembed"]');

      if (widgetElement) {
        var styles = JSON.parse(widgetElement.getAttribute('data-styles')) || {};
        styles.width = "".concat(width, "px");
        styles.height = "".concat(height, "px");
        widgetElement.setAttribute('data-styles', JSON.stringify(styles));
        var iframeElement = widgetElement.querySelector('iframe');

        if (iframeElement) {
          iframeElement.setAttribute('width', width);
          iframeElement.setAttribute('height', height);
        }
      }
    }
  };

  var selectWidget = function selectWidget(editor) {
    requestAnimationFrame(function () {
      var selection = editor.getSelection();

      if (selection) {
        var wrapperElement = selection.root.find('[data-cke-widget-wrapper]');

        if (wrapperElement) {
          var elementList = wrapperElement.$;

          if (elementList.length > 0) {
            var lastElement = new CKEDITOR.dom.element(elementList[elementList.length - 1]);
            var imageElement = lastElement.findOne('img');
            var widgetElement = lastElement.findOne('[data-widget="videoembed"]');

            if (imageElement && widgetElement) {
              var range = editor.createRange();

              if (!range) {
                return;
              }

              range.setStart(widgetElement, 0);
              range.setEnd(imageElement, 1);
              selection.selectRanges([range]);
              selection.selectElement(lastElement);
            }
          }
        }
      }
    });
  };

  var currentAlignment = null;
  var currentElement = null;
  var resizer = null;
  var EMBED_VIDEO_WIDTH = 560;
  var EMBED_VIDEO_HEIGHT = 315;
  var embedProviders = [{
    id: 'facebook',
    tpl: "<iframe allowFullScreen=\"true\" allowTransparency=\"true\"\n\t\t\t\t frameborder=\"0\" height=\"".concat(EMBED_VIDEO_HEIGHT, "\"\n\t\t\t\t src=\"https://www.facebook.com/plugins/video.php?href={embedId}'\n\t\t\t\t &show_text=0&width=").concat(EMBED_VIDEO_WIDTH, "&height=").concat(EMBED_VIDEO_HEIGHT, "\" scrolling=\"no\"\n\t\t\t\t style=\"border:none;overflow:hidden\" width=\"").concat(EMBED_VIDEO_WIDTH, "}\"></iframe>"),
    type: 'video',
    urlSchemes: ['(https?:\\/\\/(?:www\\.)?facebook.com\\/\\S*\\/videos\\/\\S*)']
  }, {
    id: 'twitch',
    tpl: "<iframe allowfullscreen=\"true\" frameborder=\"0\"\n\t\t\t\t height=\"".concat(EMBED_VIDEO_HEIGHT, "\"\n\t\t\t\t src=\"https://player.twitch.tv/?autoplay=false&video={embedId}\"\n\t\t\t\t scrolling=\"no\" width=\"").concat(EMBED_VIDEO_WIDTH, "\"></iframe>"),
    type: 'video',
    urlSchemes: ['https?:\\/\\/(?:www\\.)?twitch.tv\\/videos\\/(\\S*)$']
  }, {
    id: 'vimeo',
    tpl: "<iframe allowfullscreen frameborder=\"0\" height=\"".concat(EMBED_VIDEO_HEIGHT, "\"\n\t\t\t\t mozallowfullscreen src=\"https://player.vimeo.com/video/{embedId}\"\n\t\t\t\t webkitallowfullscreen width=\"").concat(EMBED_VIDEO_WIDTH, "\"></iframe>"),
    type: 'video',
    urlSchemes: ['https?:\\/\\/(?:www\\.)?vimeo\\.com\\/album\\/.*\\/video\\/(\\S*)', 'https?:\\/\\/(?:www\\.)?vimeo\\.com\\/channels\\/.*\\/(\\S*)', 'https?:\\/\\/(?:www\\.)?vimeo\\.com\\/groups\\/.*\\/videos\\/(\\S*)', 'https?:\\/\\/(?:www\\.)?vimeo\\.com\\/(\\S*)$']
  }, {
    id: 'youtube',
    tpl: "<iframe allow=\"autoplay; encrypted-media\" allowfullscreen\n\t\t\t\t height=\"".concat(EMBED_VIDEO_HEIGHT, "\" frameborder=\"0\"\n\t\t\t\t src=\"https://www.youtube.com/embed/{embedId}?rel=0\"\n\t\t\t\t width=\"").concat(EMBED_VIDEO_WIDTH, "\"></iframe>"),
    type: 'video',
    urlSchemes: ['https?:\\/\\/(?:www\\.)?youtube.com\\/watch\\?v=(\\S*)$', 'https?:\\/\\/(?:www\\.)?youtube.com\\/\\S*\\/([^?&]*)\\S*$', 'https?:\\/\\/(?:www\\.)?youtu.be\\/(\\S*)$']
  }]; // CSS is added in a compressed form

  CKEDITOR.addCss('img::selection{color:rgba(0,0,0,0)}img.ckimgrsz{outline:1px dashed #000}#ckimgrsz{position:absolute;width:0;height:0;cursor:default;z-index:10001}#ckimgrsz span{display:none;position:absolute;top:0;left:0;width:0;height:0;background-size:100% 100%;opacity:.65;outline:1px dashed #000}#ckimgrsz i{position:absolute;display:block;width:5px;height:5px;background:#fff;border:1px solid #000}#ckimgrsz i.active,#ckimgrsz i:hover{background:#000}#ckimgrsz i.br,#ckimgrsz i.tl{cursor:nwse-resize}#ckimgrsz i.bm,#ckimgrsz i.tm{cursor:ns-resize}#ckimgrsz i.bl,#ckimgrsz i.tr{cursor:nesw-resize}#ckimgrsz i.lm,#ckimgrsz i.rm{cursor:ew-resize}body.dragging-br,body.dragging-br *,body.dragging-tl,body.dragging-tl *{cursor:nwse-resize!important}body.dragging-bm,body.dragging-bm *,body.dragging-tm,body.dragging-tm *{cursor:ns-resize!important}body.dragging-bl,body.dragging-bl *,body.dragging-tr,body.dragging-tr *{cursor:nesw-resize!important}body.dragging-lm,body.dragging-lm *,body.dragging-rm,body.dragging-rm *{cursor:ew-resize!important}');
  /**
   * CKEditor plugin which adds the infrastructure to embed urls as media objects
   *
   * This plugin adds an `videoembed` button that can be used to easily embed a URL and transform it
   * to an embedded content.
   *
   * @class CKEDITOR.plugins.videoembed
   */

  CKEDITOR.plugins.add('videoembed', {
    _defaultEmbedWidgetUpcastFn: function _defaultEmbedWidgetUpcastFn(editor, element, data) {
      var upcastWidget = false;

      if (element.name === 'div' && element.attributes['data-embed-url']) {
        data.url = element.attributes['data-embed-url'];
        upcastWidget = true;
      } else if (element.name === 'div' && element.attributes['data-embed-id']) {
        var iframe = element.children[0];
        data.url = iframe.attributes.src;
        delete element.attributes.style;

        var embedContent = this._generateEmbedContent(editor, data.url, element.getOuterHtml());

        var widgetFragment = new CKEDITOR.htmlParser.fragment.fromHtml(embedContent);
        upcastWidget = widgetFragment.children[0];
        upcastWidget.attributes['data-styles'] = element.attributes['data-styles'];
        upcastWidget.removeClass('embed-responsive');
        upcastWidget.removeClass('embed-responsive-16by9');
        element.replaceWith(upcastWidget);
      }

      return upcastWidget;
    },
    _generateEmbedContent: function _generateEmbedContent(editor, url, content) {
      return this._getWidgetTemplate(editor).output({
        content: content,
        helpMessage: Liferay.Language.get('video-playback-is-disabled-during-edit-mode'),
        helpMessageIcon: Liferay.Util.getLexiconIconTpl('info-circle'),
        url: url
      });
    },
    _getProviders: function _getProviders(editor) {
      var providers = editor.config.embedProviders || embedProviders;
      return providers.map(function (provider) {
        return {
          id: provider.id,
          tpl: new CKEDITOR.template("<div data-embed-id=\"{embedId}\">".concat(provider.tpl, "</div>")),
          type: provider.type,
          urlSchemes: provider.urlSchemes.map(function (scheme) {
            return new RegExp(scheme);
          })
        };
      });
    },
    _getWidgetTemplate: function _getWidgetTemplate(editor) {
      return new CKEDITOR.template(editor.config.embedWidgetTpl || CKEDITOR.DEFAULT_LFR_EMBED_WIDGET_TPL);
    },
    _showError: function _showError(editor, errorMsg) {
      Liferay.Util.openToast({
        message: errorMsg,
        type: 'danger'
      });
      setTimeout(function () {
        editor.getSelection().removeAllRanges();
        editor.focus();
        resizer.hide();
      }, 0);
    },
    afterInit: function afterInit(editor) {
      editor.on('resize', function () {
        resizer.hide();
        selectWidget(editor);
      });
      ALIGN_VALUES.forEach(function (alignValue) {
        var command = editor.getCommand('justify' + alignValue);

        if (command) {
          command.on('exec', function (event) {
            var selectedElement = editor.getSelection().getSelectedElement();

            if (selectedElement && selectedElement.getAttribute('data-cke-widget-wrapper')) {
              var selectedEmbed = selectedElement.findOne('[data-widget="videoembed"] [data-embed-id]');

              if (selectedEmbed) {
                var embedAlignment = getEmbedAlignment(selectedElement);

                if (embedAlignment === alignValue) {
                  removeEmbedAlignment(selectedElement, alignValue);
                } else {
                  setEmbedAlignment(selectedElement, alignValue);
                }

                currentElement = selectedElement;
                currentAlignment = getEmbedAlignment(selectedElement);
                var imageElement = selectedElement.findOne('img');

                if (imageElement) {
                  resizer.show(imageElement.$);
                }

                event.cancel();
                var elementPath = new CKEDITOR.dom.elementPath(selectedElement);
                ALIGN_VALUES.forEach(function (alignValue) {
                  var command = editor.getCommand('justify' + alignValue);

                  if (command) {
                    command.refresh(editor, elementPath);
                  }
                });
              }
            }
          });
          command.on('refresh', function (event) {
            var lastElement = event.data.path.lastElement;

            if (lastElement && lastElement.getAttribute('data-cke-widget-wrapper') && lastElement.findOne('[data-widget] [data-embed-id]')) {
              var embedAlignment = getEmbedAlignment(lastElement);
              event.sender.setState(embedAlignment === alignValue ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF);
              event.cancel();
            }
          });
        }
      });
    },
    init: function init(editor) {
      var instance = this;
      editor.widgets.add('videoembed', {
        data: function data(event) {
          var instance = this;
          var stylesJSON = instance.element.getAttribute('data-styles');
          var styles = stylesJSON ? JSON.parse(stylesJSON) : null;

          if (!styles) {
            var iframe = instance.wrapper.findOne('iframe');
            var bounds = instance.wrapper.$.getBoundingClientRect();
            var width = iframe.getAttribute('width');
            var pwidth = width >= bounds.width ? 100 : Math.round(width / bounds.width * 100);
            styles = {
              width: "".concat(pwidth, "%")
            };
          }

          instance.wrapper.setAttribute('style', CKEDITOR.tools.writeCssText(styles));
          var doc = instance.wrapper.getDocument();
          doc.appendStyleSheet('/o/frontend-css-web/main.css');

          function mouseDownListener(event) {
            var result = getSelectedElement(editor);
            currentAlignment = result.alignment;
            currentElement = result.element;

            if (resizer.isHandle(event.target)) {
              resizer.initDrag(event);
            }
          }

          doc.$.addEventListener('mousedown', mouseDownListener);
          var body = doc.getBody();

          if (body) {
            body.addClass('cke_editor_content');
          }

          if (editor._selectEmbedWidget === event.data.url) {
            selectWidget(editor);
          }
        },
        downcast: function downcast(widget) {
          var embedContent = widget.children[0];
          embedContent.attributes.class = 'embed-responsive embed-responsive-16by9';
          embedContent.attributes['data-styles'] = JSON.stringify(CKEDITOR.tools.parseCssText(widget.parent.attributes.style));
          embedContent.attributes.style = widget.parent.attributes.style;
          return embedContent;
        },
        draggable: false,
        mask: true,
        requiredContent: 'div[data-embed-url]',
        upcast: function upcast(element, data) {
          var embedWidgetUpcastFn = editor.config.embedWidgetUpcastFn || instance._defaultEmbedWidgetUpcastFn.bind(instance);

          return embedWidgetUpcastFn(editor, element, data);
        }
      });
      editor.addCommand('videoembed', new CKEDITOR.dialogCommand('videoembedDialog'));

      if (editor.ui.addButton) {
        editor.ui.addButton('VideoEmbed', {
          command: 'videoembed',
          icon: instance.path + 'icons/video.png',
          label: Liferay.Language.get('video')
        });
      }

      CKEDITOR.dialog.add('videoembedDialog', instance.path + 'dialogs/videoembedDialog.js');
      window.addEventListener('resize', function () {
        resizer.hide();
        selectWidget(editor);
      }, false);
      editor.on('selectionChange', function (_event) {
        var selection = editor.getSelection();

        if (selection) {
          var element = selection.getSelectedElement();

          if (element) {
            var widgetElement = element.findOne('[data-widget="videoembed"]');

            if (widgetElement) {
              var scrollPosition = new CKEDITOR.dom.window(window).getScrollPosition();
              var region = element.getClientRect();
              region.direction = CKEDITOR.SELECTION_BOTTOM_TO_TOP;
              region.left -= scrollPosition.x;
              region.top += scrollPosition.y;
              editor.fire('editorInteraction', {
                nativeEvent: {},
                selectionData: {
                  element: widgetElement,
                  region: region
                }
              });
            }

            var imageElement = element.findOne('img.cke_widget_mask');

            if (imageElement) {
              resizer.show(imageElement.$);
            }
          } else {
            resizer.hide();
          }
        }
      });
      editor.on('destroy', function () {
        var resizeElement = document.getElementById('ckimgrsz');

        if (resizeElement) {
          resizeElement.remove();
        }
      });
      editor.on('blur', function () {
        resizer.hide();
      });
      editor.filter.addElementCallback(function (element) {
        if ('data-embed-url' in element.attributes) {
          return CKEDITOR.FILTER_SKIP_TREE;
        }
      });
      var path = instance.path;
      var dependencies = [CKEDITOR.getUrl(path + 'DragEvent.es.js'), CKEDITOR.getUrl(path + 'Resizer.es.js')];
      CKEDITOR.scriptLoader.load(dependencies, function () {
        resizer = new Liferay.ResizerCKEditor(editor, {
          onComplete: function onComplete(element, width, height) {
            resizeElement(element, width, height);

            if (currentAlignment && currentElement) {
              setEmbedAlignment(currentElement, currentAlignment);
            }

            selectWidget(editor);
          }
        });
      });
    },
    onOkVideo: function onOkVideo(editor, data) {
      var type = data.type;
      var url = data.url;
      var content;

      if (REGEX_HTTP.test(url)) {
        var validProvider = this._getProviders(editor).filter(function (provider) {
          return type ? provider.type === type : true;
        }).some(function (provider) {
          var scheme = provider.urlSchemes.find(function (scheme) {
            return scheme.test(url);
          });

          if (scheme) {
            var embedId = scheme.exec(url)[1];
            content = provider.tpl.output({
              embedId: embedId
            });
          }

          return scheme;
        });

        if (validProvider) {
          editor._selectEmbedWidget = url;

          var embedContent = this._generateEmbedContent(editor, url, content);

          editor.insertHtml(embedContent);
        } else {
          this._showError(editor, Liferay.Language.get('sorry,-this-platform-is-not-supported'));
        }
      } else {
        this._showError(editor, Liferay.Language.get('enter-a-valid-url'));
      }
    },
    requires: 'widget'
  });
}
//# sourceMappingURL=plugin.js.map