function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
import { EditorState, TextSelection, Plugin, PluginKey } from 'prosemirror-state';
import { Transform } from 'prosemirror-transform';
import { Decoration, DecorationSet, EditorView } from 'prosemirror-view';
import { IMAGE } from './NodeNames.js';
import uuid from './ui/uuid.js';
var IMAGE_FILE_TYLES = new Set(['image/jpeg', 'image/gif', 'image/png', 'image/jpg']);
var TITLE = 'Uploading...';
var INNER_HTML = new Array(4).join('<div class="czi-image-upload-placeholder-child"></div>');
function isImageUploadPlaceholderPlugin(plugin) {
  return plugin instanceof ImageUploadPlaceholderPlugin;
}
function isImageFileType(file) {
  return file && IMAGE_FILE_TYLES.has(file.type);
}
function findImageUploadPlaceholder(placeholderPlugin, state, id) {
  var decos = placeholderPlugin.getState(state);
  var found = decos.find(null, null, function (spec) {
    return spec.id === id;
  });
  return found.length ? found[0].from : null;
}
function defer(fn) {
  return function () {
    setTimeout(fn, 0);
  };
}
export function uploadImageFiles(view, files, coords) {
  var runtime = view.runtime,
    state = view.state,
    readOnly = view.readOnly,
    disabled = view.disabled;
  var schema = state.schema,
    plugins = state.plugins;
  if (readOnly || disabled || !(runtime !== null && runtime !== void 0 && runtime.canUploadImage)) {
    return false;
  }
  var imageType = schema.nodes[IMAGE];
  if (!imageType) {
    return false;
  }
  var uploadImage = runtime.uploadImage,
    canUploadImage = runtime.canUploadImage;
  if (!uploadImage || !canUploadImage) {
    return false;
  }
  var imageFiles = Array.from(files).filter(isImageFileType);
  if (!imageFiles.length) {
    return false;
  }
  var placeholderPlugin = plugins.find(isImageUploadPlaceholderPlugin);
  if (!placeholderPlugin) {
    return false;
  }

  // A fresh object to act as the ID for this upload.
  var id = {
    debugId: 'image_upload_' + uuid()
  };
  var uploadNext = defer(function () {
    var done = function done(imageInfo) {
      var pos = findImageUploadPlaceholder(placeholderPlugin, view.state, id);
      var trNext = view.state.tr;
      if (pos && !view.readOnly && !view.disabled) {
        var imageNode = imageType.create(imageInfo);
        trNext = trNext.replaceWith(pos, pos, imageNode);
      } else {
        // Upload was cancelled.
        imageFiles.length = 0;
      }
      if (imageFiles.length) {
        uploadNext();
      } else {
        // Remove the placeholder.
        trNext = trNext.setMeta(placeholderPlugin, {
          remove: {
            id: id
          }
        });
      }
      view.dispatch(trNext);
    };
    var ff = imageFiles === null || imageFiles === void 0 ? void 0 : imageFiles.shift();
    uploadImage(ff).then(done)["catch"](done.bind(null, {
      src: null
    }));
  });
  uploadNext();
  var tr = state.tr;

  // Replace the selection with a placeholder
  var from = 0;

  // Adjust the cursor to the dropped position.
  if (coords) {
    var dropPos = view.posAtCoords({
      left: coords.x,
      top: coords.y
    });
    if (!dropPos) {
      return false;
    }
    from = dropPos.pos;
    tr = tr.setSelection(TextSelection.create(tr.doc, from, from));
  } else {
    from = tr.selection.to;
    tr = tr.setSelection(TextSelection.create(tr.doc, from, from));
  }
  var meta = {
    add: {
      id: id,
      pos: from
    }
  };
  tr = tr.setMeta(placeholderPlugin, meta);
  view.dispatch(tr);
  return true;
}

// https://prosemirror.net/examples/upload/
var ImageUploadPlaceholderPlugin = /*#__PURE__*/function (_Plugin) {
  function ImageUploadPlaceholderPlugin() {
    _classCallCheck(this, ImageUploadPlaceholderPlugin);
    return _callSuper(this, ImageUploadPlaceholderPlugin, [{
      // [FS] IRAD-1005 2020-07-07
      // Upgrade outdated packages.
      key: new PluginKey('ImageUploadPlaceholderPlugin'),
      state: {
        init: function init() {
          return DecorationSet.empty;
        },
        apply: function apply(tr, set) {
          // Adjust decoration positions to changes made by the transaction
          set = set.map(tr.mapping, tr.doc);
          // See if the transaction adds or removes any placeholders
          var action = tr.getMeta(this);
          if (action !== null && action !== void 0 && action.add) {
            var el = document.createElement('div');
            el.title = TITLE;
            el.className = 'czi-image-upload-placeholder';
            el.innerHTML = INNER_HTML;
            var deco = Decoration.widget(action.add.pos, el, {
              id: action.add.id
            });
            set = set.add(tr.doc, [deco]);
          } else if (action !== null && action !== void 0 && action.remove) {
            var finder = function finder(spec) {
              return spec.id == action.remove.id;
            };
            set = set.remove(set.find(null, null, finder));
          }
          return set;
        }
      },
      props: {
        decorations: function decorations(state) {
          return this.getState(state);
        }
      }
    }]);
  }
  _inherits(ImageUploadPlaceholderPlugin, _Plugin);
  return _createClass(ImageUploadPlaceholderPlugin);
}(Plugin);
export default ImageUploadPlaceholderPlugin;