import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import { linkify } from '@atlaskit/adf-schema';
import { DONTLINKIFY_REGEXP } from './hyperlink';

/* eslint-enable require-unicode-regexp */
/**
 * Instance of class LinkMatcher are used in autoformatting in place of Regex.
 * Hence it has been made similar to regex with an exec method.
 * Extending it directly from class Regex was introducing some issues, thus that has been avoided.
 */
export var LinkMatcher = /*#__PURE__*/function () {
  function LinkMatcher() {
    _classCallCheck(this, LinkMatcher);
  }
  return _createClass(LinkMatcher, null, [{
    key: "create",
    value: function create() {
      var LinkMatcherRegex = /*#__PURE__*/function () {
        function LinkMatcherRegex() {
          _classCallCheck(this, LinkMatcherRegex);
        }
        return _createClass(LinkMatcherRegex, [{
          key: "exec",
          value: function exec(str) {
            var stringsBySpace = str.slice(0, str.length - 1).split(' ');
            var lastStringBeforeSpace = stringsBySpace[stringsBySpace.length - 1];
            var isLastStringValid = lastStringBeforeSpace.length > 0;
            if (!str.endsWith(' ') || !isLastStringValid) {
              return null;
            }
            if (DONTLINKIFY_REGEXP.test(lastStringBeforeSpace)) {
              return null;
            }
            var links = linkify.match(lastStringBeforeSpace);
            if (!links || links.length === 0) {
              return null;
            }
            var lastMatch = links[links.length - 1];
            var lastLink = links[links.length - 1];
            lastLink.input = str.substring(lastMatch.index);
            lastLink.length = lastLink.lastIndex - lastLink.index + 1;
            lastLink.index = str.lastIndexOf(lastStringBeforeSpace) + lastMatch.index;
            return lastLink;
          }
        }]);
      }();
      return new LinkMatcherRegex();
    }
  }]);
}();