define([
  'summernote/core/list',
  'summernote/core/dom'
], function (list, dom) {
  var Clipboard = function (handler) {

    this.attach = function (layoutInfo) {
      layoutInfo.editable().on('paste', hPasteClipboardImage);
    };

    /**
     * paste clipboard image
     *
     * @param {Event} event
     */
    var hPasteClipboardImage = function (event) {
      var clipboardData = event.originalEvent.clipboardData;
      var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target);
      var $editable = layoutInfo.editable();

      if (!clipboardData || !clipboardData.items || !clipboardData.items.length) {
        var callbacks = $editable.data('callbacks');
        // only can run if it has onImageUpload method
        if (!callbacks.onImageUpload) {
          return;
        }

        // save cursor
        handler.invoke('editor.saveNode', $editable);
        handler.invoke('editor.saveRange', $editable);

        $editable.html('');

        setTimeout(function () {
          var $img = $editable.find('img');

          // if img is no in clipboard, insert text or dom
          if (!$img.length || $img[0].src.indexOf('data:') === -1) {
            var html = $editable.html();

            handler.invoke('editor.restoreNode', $editable);
            handler.invoke('editor.restoreRange', $editable);

            handler.invoke('editor.focus', $editable);
            try {
              handler.invoke('editor.pasteHTML', $editable, html);
            } catch (ex) {
              handler.invoke('editor.insertText', $editable, html);
            }
            return;
          }

          var datauri = $img[0].src;

          var data = atob(datauri.split(',')[1]);
          var array = new Uint8Array(data.length);
          for (var i = 0; i < data.length; i++) {
            array[i] = data.charCodeAt(i);
          }

          var blob = new Blob([array], { type : 'image/png' });
          blob.name = 'clipboard.png';

          handler.invoke('editor.restoreNode', $editable);
          handler.invoke('editor.restoreRange', $editable);
          handler.insertImages(layoutInfo, [blob]);

          handler.invoke('editor.afterCommand', $editable);
        }, 0);

        return;
      }

      var item = list.head(clipboardData.items);
      var isClipboardImage = item.kind === 'file' && item.type.indexOf('image/') !== -1;

      if (isClipboardImage) {
        handler.insertImages(layoutInfo, [item.getAsFile()]);
      }

      handler.invoke('editor.afterCommand', $editable);
    };
  };

  return Clipboard;
});
