define(["exports", "core/pubsubhub", "core/biblio", "deps/regenerator"], function (exports, _pubsubhub, _biblio) {
  "use strict";

  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.linkInlineCitations = exports.run = exports.name = undefined;

  function _asyncToGenerator(fn) {
    return function () {
      var gen = fn.apply(this, arguments);
      return new Promise(function (resolve, reject) {
        function step(key, arg) {
          try {
            var info = gen[key](arg);
            var value = info.value;
          } catch (error) {
            reject(error);
            return;
          }

          if (info.done) {
            resolve(value);
          } else {
            return Promise.resolve(value).then(function (value) {
              step("next", value);
            }, function (err) {
              step("throw", err);
            });
          }
        }

        return step("next");
      });
    };
  }

  var name = exports.name = "core/data-cite";

  function requestLookup(conf) {
    var toCiteDetails = citeDetailsConverter(conf);
    return function () {
      var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(elem) {
        var originalKey, _toCiteDetails, key, frag, href, entry, msg, a;

        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                originalKey = elem.dataset.cite;
                _toCiteDetails = toCiteDetails(elem), key = _toCiteDetails.key, frag = _toCiteDetails.frag;
                href = "";
                // This is just referring to this document

                if (!(key === conf.shortName)) {
                  _context.next = 7;
                  break;
                }

                href = document.location.href;
                _context.next = 18;
                break;

              case 7:
                _context.next = 9;
                return (0, _biblio.resolveRef)(key);

              case 9:
                entry = _context.sent;

                cleanElement(elem);

                if (entry) {
                  _context.next = 17;
                  break;
                }

                msg = "Couldn't find a match for 'data-cite=" + originalKey + "'.";

                console.warn(msg, elem);
                msg += " Please check developer console for offending element.";
                (0, _pubsubhub.pub)("warn", msg);
                return _context.abrupt("return");

              case 17:
                href = entry.href;

              case 18:
                if (frag) {
                  href = new URL(frag, href).href;
                }
                _context.t0 = elem.localName;
                _context.next = _context.t0 === "a" ? 22 : _context.t0 === "dfn" ? 24 : 29;
                break;

              case 22:
                elem.href = href;
                return _context.abrupt("break", 29);

              case 24:
                a = elem.ownerDocument.createElement("a");

                a.href = href;
                while (elem.firstChild) {
                  a.appendChild(elem.firstChild);
                }
                elem.appendChild(a, elem);
                return _context.abrupt("break", 29);

              case 29:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }();
  }

  function cleanElement(elem) {
    ["data-cite", "data-cite-frag"].filter(function (attrName) {
      return elem.hasAttribute(attrName);
    }).forEach(function (attrName) {
      return elem.removeAttribute(attrName);
    });
  }

  function citeDetailsConverter(conf) {
    return function toCiteDetails(elem) {
      var dataset = elem.dataset;
      var key = dataset.cite,
          frag = dataset.citeFrag;

      var isNormative = key.startsWith("!");
      var fragPosition = key.search("#");
      // The key is a fragment, resolve using the shortName as key
      if (key.startsWith("#") && !frag) {
        // Closes data-cite not starting with "#"
        var closest = elem.parentElement.closest("[data-cite]:not([data-cite^=\"#\"])");

        var _ref2 = closest ? toCiteDetails(closest) : { key: conf.shortName || "", isNormative: false },
            parentKey = _ref2.key,
            closestIsNormative = _ref2.isNormative;

        elem.dataset.cite = closestIsNormative ? "!" + parentKey : parentKey;
        elem.dataset.citeFrag = key; // the key is acting as fragment
        return toCiteDetails(elem);
      }
      if (fragPosition !== -1) {
        frag = !frag ? key.substr(fragPosition) : frag;
        key = key.substring(0, fragPosition);
      }
      if (isNormative) {
        key = key.substr(1);
      }
      if (frag && !frag.startsWith("#")) {
        frag = "#" + frag;
      }
      return { key: key, isNormative: isNormative, frag: frag };
    };
  }

  var run = exports.run = function () {
    var _ref3 = _asyncToGenerator(regeneratorRuntime.mark(function _callee2(conf) {
      var toCiteDetails;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              toCiteDetails = citeDetailsConverter(conf);

              Array.from(document.querySelectorAll(["dfn[data-cite], a[data-cite]"])).filter(function (el) {
                return el.dataset.cite;
              }).map(toCiteDetails).reduce(function (conf, _ref4) {
                var isNormative = _ref4.isNormative,
                    key = _ref4.key;

                if (isNormative) {
                  conf.normativeReferences.add(key);
                } else {
                  conf.informativeReferences.add(key);
                }
                return conf;
              }, conf);

            case 2:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, this);
    }));

    return function run(_x2) {
      return _ref3.apply(this, arguments);
    };
  }();

  var linkInlineCitations = exports.linkInlineCitations = function () {
    var _ref5 = _asyncToGenerator(regeneratorRuntime.mark(function _callee3(doc) {
      var conf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : respecConfig;
      var toLookupRequest, citedSpecs, lookupRequests;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              toLookupRequest = requestLookup(conf);
              citedSpecs = doc.querySelectorAll("dfn[data-cite], a[data-cite]");
              lookupRequests = Array.from(citedSpecs).map(toLookupRequest);
              _context3.next = 5;
              return Promise.all(lookupRequests);

            case 5:
              return _context3.abrupt("return", _context3.sent);

            case 6:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, this);
    }));

    return function linkInlineCitations(_x4) {
      return _ref5.apply(this, arguments);
    };
  }();
});
//# sourceMappingURL=data-cite.js.map