import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _typeof from "@babel/runtime/helpers/typeof";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import * as clipboard from 'clipboard-polyfill';
import { TextSelection } from '@atlaskit/editor-prosemirror/state';
import { ACTION_SUBJECT, ACTION_SUBJECT_ID, EVENT_TYPE } from '../analytics';
import { getAllSelectionAnalyticsPayload, getCellSelectionAnalyticsPayload, getNodeSelectionAnalyticsPayload, getRangeSelectionAnalyticsPayload } from '../selection';
var isClipboardApiSupported = function isClipboardApiSupported() {
  return !!navigator.clipboard && typeof navigator.clipboard.writeText === 'function';
};
var isIEClipboardApiSupported = function isIEClipboardApiSupported() {
  return window.clipboardData && typeof window.clipboardData.setData === 'function';
};
var isExtensionNode = function isExtensionNode(node) {
  if (node === 'extension' || node === 'bodiedExtension' || node === 'inlineExtension' || node === 'multiBodiedExtension') {
    return true;
  }
  return false;
};
export var copyToClipboard = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(textToCopy) {
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!isClipboardApiSupported()) {
            _context.next = 11;
            break;
          }
          _context.prev = 1;
          _context.next = 4;
          return navigator.clipboard.writeText(textToCopy);
        case 4:
          _context.next = 9;
          break;
        case 6:
          _context.prev = 6;
          _context.t0 = _context["catch"](1);
          throw new Error('Clipboard api is not supported');
        case 9:
          _context.next = 23;
          break;
        case 11:
          if (!isIEClipboardApiSupported()) {
            _context.next = 22;
            break;
          }
          _context.prev = 12;
          _context.next = 15;
          return window.clipboardData.setData('text', textToCopy);
        case 15:
          _context.next = 20;
          break;
        case 17:
          _context.prev = 17;
          _context.t1 = _context["catch"](12);
          throw new Error('IE clipboard api is not supported');
        case 20:
          _context.next = 23;
          break;
        case 22:
          throw new Error('Clipboard api is not supported');
        case 23:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[1, 6], [12, 17]]);
  }));
  return function copyToClipboard(_x) {
    return _ref.apply(this, arguments);
  };
}();
export var copyHTMLToClipboard = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(elementToCopy, plainTextToCopy) {
    var data;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (!(isClipboardApiSupported() && typeof ClipboardItem !== 'undefined')) {
            _context2.next = 12;
            break;
          }
          _context2.prev = 1;
          data = new ClipboardItem({
            'text/plain': new Blob([plainTextToCopy || elementToCopy.innerText], {
              type: 'text/plain'
            }),
            'text/html': new Blob([elementToCopy.innerHTML], {
              type: 'text/html'
            })
          }); // @ts-ignore
          _context2.next = 5;
          return navigator.clipboard.write([data]);
        case 5:
          _context2.next = 10;
          break;
        case 7:
          _context2.prev = 7;
          _context2.t0 = _context2["catch"](1);
          throw new Error('Clipboard api is not supported');
        case 10:
          _context2.next = 13;
          break;
        case 12:
          if ((typeof document === "undefined" ? "undefined" : _typeof(document)) !== undefined) {
            // ED-17083 extension copy seems have issue with ClipboardItem API
            // Hence of use of this polyfill
            copyHTMLToClipboardPolyfill(elementToCopy, plainTextToCopy);
          }
        case 13:
        case "end":
          return _context2.stop();
      }
    }, _callee2, null, [[1, 7]]);
  }));
  return function copyHTMLToClipboard(_x2, _x3) {
    return _ref2.apply(this, arguments);
  };
}();

// At the time of development, Firefox doesn't support ClipboardItem API
// Hence of use of this polyfill
export var copyHTMLToClipboardPolyfill = function copyHTMLToClipboardPolyfill(elementToCopy, plainTextToCopy) {
  var Clipboard = clipboard;
  var dt = new Clipboard.DT();
  dt.setData('text/plain', plainTextToCopy || elementToCopy.innerText);
  dt.setData('text/html', elementToCopy.innerHTML);
  Clipboard.write(dt);
};
export var getAnalyticsPayload = function getAnalyticsPayload(state, action) {
  var selection = state.selection,
    doc = state.doc;
  var selectionAnalyticsPayload = getNodeSelectionAnalyticsPayload(selection) || getRangeSelectionAnalyticsPayload(selection, doc) || getAllSelectionAnalyticsPayload(selection) || getCellSelectionAnalyticsPayload(state);
  if (selectionAnalyticsPayload) {
    var _attributes;
    var selectionActionSubjectId = selectionAnalyticsPayload.actionSubjectId;
    var node = (_attributes = selectionAnalyticsPayload.attributes) === null || _attributes === void 0 ? void 0 : _attributes.node;
    var content = [];
    var extensionType;
    var extensionKey;
    switch (selectionActionSubjectId) {
      case ACTION_SUBJECT_ID.NODE:
        if (node) {
          content.push(node);
          if (isExtensionNode(node)) {
            extensionType = selection.node.attrs.extensionType;
            extensionKey = selection.node.attrs.extensionKey;
          }
        }
        break;
      case ACTION_SUBJECT_ID.RANGE:
        content.push.apply(content, _toConsumableArray(selectionAnalyticsPayload.attributes.nodes));
        break;
      case ACTION_SUBJECT_ID.ALL:
        content.push('all');
        break;
      case ACTION_SUBJECT_ID.CELL:
        {
          var _ref3 = selectionAnalyticsPayload.attributes,
            selectedCells = _ref3.selectedCells;
          content.push.apply(content, _toConsumableArray(Array(selectedCells).fill('tableCell')));
          break;
        }
    }
    if (isExtensionNode(node)) {
      return {
        eventType: EVENT_TYPE.TRACK,
        action: action,
        actionSubject: ACTION_SUBJECT.DOCUMENT,
        attributes: {
          content: content,
          extensionKey: extensionKey,
          extensionType: extensionType
        }
      };
    }
    return {
      eventType: EVENT_TYPE.TRACK,
      action: action,
      actionSubject: ACTION_SUBJECT.DOCUMENT,
      attributes: {
        content: content
      }
    };
  }
  if (selection instanceof TextSelection && selection.$cursor) {
    return {
      eventType: EVENT_TYPE.TRACK,
      action: action,
      actionSubject: ACTION_SUBJECT.DOCUMENT,
      attributes: {
        content: ['caret']
      }
    };
  }
};