"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.editInsertedLink = editInsertedLink;
exports.hideLinkToolbar = hideLinkToolbar;
exports.insertLink = insertLink;
exports.isLinkAtPos = isLinkAtPos;
exports.isTextAtPos = isTextAtPos;
exports.removeLink = removeLink;
exports.setLinkHref = setLinkHref;
exports.setLinkText = setLinkText;
exports.updateLink = updateLink;

var _utils = require("./utils");

var _main = require("./pm-plugins/main");

var _prosemirrorState = require("prosemirror-state");

var _commands = require("../../../utils/commands");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

// import {
//   addAnalytics,
//   ACTION,
//   ACTION_SUBJECT,
//   INPUT_METHOD,
//   EVENT_TYPE,
//   ACTION_SUBJECT_ID,
//   withAnalytics,
// } from '../analytics';
// import { queueCardsFromChangedTr } from '../card/pm-plugins/doc';
// import { LinkInputType } from './ui/HyperlinkAddToolbar/HyperlinkAddToolbar';
// import { getLinkCreationAnalyticsEvent } from './analytics';
function isTextAtPos(pos) {
  return function (state) {
    var node = state.doc.nodeAt(pos);
    return !!node && node.isText;
  };
}

function isLinkAtPos(pos) {
  return function (state) {
    var node = state.doc.nodeAt(pos);
    return !!node && state.schema.marks.link.isInSet(node.marks);
  };
}

function setLinkHref(href, pos, to, isTabPressed) {
  return (0, _commands.filter)(isTextAtPos(pos), function (state, dispatch) {
    var $pos = state.doc.resolve(pos);
    var node = state.doc.nodeAt(pos);
    var linkMark = state.schema.marks.link;
    var mark = linkMark.isInSet(node.marks);
    var url = (0, _utils.normalizeUrl)(href);

    if (mark && mark.attrs.href === url) {
      return false;
    }

    var rightBound = to && pos !== to ? to : pos - $pos.textOffset + node.nodeSize;
    var tr = state.tr.removeMark(pos, rightBound, linkMark);

    if (href.trim()) {
      tr.addMark(pos, rightBound, linkMark.create(_objectSpread(_objectSpread({}, mark && mark.attrs || {}), {}, {
        href: url
      })));
    }

    if (!isTabPressed) {
      tr.setMeta(_main.stateKey, {
        type: _main.LinkAction.HIDE_TOOLBAR
      });
    }

    if (dispatch) {
      dispatch(tr);
    }

    return true;
  });
}

function updateLink(href, text, pos, to) {
  return function (state, dispatch) {
    var $pos = state.doc.resolve(pos);
    var node = state.doc.nodeAt(pos);

    if (!node) {
      return false;
    }

    var url = (0, _utils.normalizeUrl)(href);

    if (!url) {
      return false;
    }

    var mark = state.schema.marks.link.isInSet(node.marks);
    var linkMark = state.schema.marks.link;
    var rightBound = to && pos !== to ? to : pos - $pos.textOffset + node.nodeSize;
    var tr = state.tr;
    tr.insertText(text, pos, rightBound); // Casting to LinkAttributes to prevent wrong attributes been passed (Example ED-7951)

    var linkAttrs = _objectSpread(_objectSpread({}, mark && mark.attrs || {}), {}, {
      href: url
    });

    tr.addMark(pos, pos + text.length, linkMark.create(linkAttrs));
    tr.setMeta(_main.stateKey, {
      type: _main.LinkAction.HIDE_TOOLBAR
    });

    if (dispatch) {
      dispatch(tr);
    }

    return true;
  };
}

function setLinkText(text, pos, to) {
  return (0, _commands.filter)(isLinkAtPos(pos), function (state, dispatch) {
    var $pos = state.doc.resolve(pos);
    var node = state.doc.nodeAt(pos);
    var mark = state.schema.marks.link.isInSet(node.marks);

    if (node && text.length > 0 && text !== node.text) {
      var rightBound = to && pos !== to ? to : pos - $pos.textOffset + node.nodeSize;
      var tr = state.tr;
      tr.insertText(text, pos, rightBound);
      tr.addMark(pos, pos + text.length, mark);
      tr.setMeta(_main.stateKey, {
        type: _main.LinkAction.HIDE_TOOLBAR
      });

      if (dispatch) {
        dispatch(tr);
      }

      return true;
    }

    return false;
  });
}

function insertLink(from, to, href, text // source?: INPUT_METHOD.MANUAL | INPUT_METHOD.TYPEAHEAD,
) {
  return (0, _commands.filter)((0, _main.canLinkBeCreatedInRange)(from, to), function (state, dispatch) {
    var link = state.schema.marks.link;

    if (href.trim()) {
      var tr = state.tr;
      var normalizedUrl = (0, _utils.normalizeUrl)(href);

      if (from === to) {
        var textContent = text || href;
        tr.insertText(textContent, from, to);
        tr.addMark(from, from + textContent.length, link.create({
          href: normalizedUrl
        }));
      } else {
        var _textContent = text || href;

        tr.insertText(_textContent, from, to);
        tr.addMark(from, from + _textContent.length, link.create({
          href: normalizedUrl
        }));
        tr.setSelection(_prosemirrorState.Selection.near(tr.doc.resolve(from + _textContent.length)));
      } // queueCardsFromChangedTr(state, tr, source!, false);


      tr.setMeta(_main.stateKey, {
        type: _main.LinkAction.HIDE_TOOLBAR
      });

      if (dispatch) {
        dispatch(tr);
      }

      return true;
    }

    return false;
  });
} // export const insertLinkWithAnalytics = (
//   inputMethod: LinkInputType,
//   from: number,
//   to: number,
//   href: string,
//   text?: string,
// ) =>
//   withAnalytics(getLinkCreationAnalyticsEvent(inputMethod, href))(
//     insertLink(from, to, href, text, inputMethod),
//   );


function removeLink(pos) {
  return setLinkHref('', pos);
}

function editInsertedLink() {
  return function (state, dispatch) {
    if (dispatch) {
      dispatch(state.tr.setMeta(_main.stateKey, {
        type: _main.LinkAction.EDIT_INSERTED_TOOLBAR
      }));
    }

    return true;
  };
} // export function showLinkToolbar(
//   inputMethod:
//     | INPUT_METHOD.TOOLBAR
//     | INPUT_METHOD.QUICK_INSERT
//     | INPUT_METHOD.SHORTCUT
//     | INPUT_METHOD.INSERT_MENU = INPUT_METHOD.TOOLBAR,
// ): Command {
//   return function(state, dispatch) {
//     if (dispatch) {
//       let tr = state.tr.setMeta(stateKey, {
//         type: LinkAction.SHOW_INSERT_TOOLBAR,
//       });
//       tr = addAnalytics(state, tr, {
//         action: ACTION.INVOKED,
//         actionSubject: ACTION_SUBJECT.TYPEAHEAD,
//         actionSubjectId: ACTION_SUBJECT_ID.TYPEAHEAD_LINK,
//         attributes: { inputMethod },
//         eventType: EVENT_TYPE.UI,
//       });
//       dispatch(tr);
//     }
//     return true;
//   };
// }


function hideLinkToolbar() {
  return function (state, dispatch) {
    if (dispatch) {
      dispatch(state.tr.setMeta(_main.stateKey, {
        type: _main.LinkAction.HIDE_TOOLBAR
      }));
    }

    return true;
  };
}