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

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

  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");
      });
    };
  }

  function processResponse(rawData, id, url) {
    var el = document.querySelector("[data-include-id=" + id + "]");
    var doc = el.ownerDocument;
    var data = (0, _utils.runTransforms)(rawData, el.dataset.oninclude, url);
    var replace = typeof el.dataset.includeReplace === "string";
    var replacementNode = void 0;
    switch (el.dataset.includeFormat) {
      case "text":
        if (replace) {
          replacementNode = doc.createTextNode(data);
          el.parentNode.replaceChild(replacementNode, el);
        } else {
          el.textContent = data;
        }
        break;
      default:
        // html, which is just using "innerHTML"
        el.innerHTML = data;
        if (replace) {
          replacementNode = doc.createDocumentFragment();
          while (el.hasChildNodes()) {
            replacementNode.append(el.removeChild(el.firstChild));
          }
          el.parentNode.replaceChild(replacementNode, el);
        }
    }
    // If still in the dom tree, clean up
    if (doc.contains(el)) {
      cleanUp(el);
    }
  }
  /**
   * Removes attributes after they are used for inclusion, if present.
   *
   * @param {Element} el The element to clean up.
   */
  function cleanUp(el) {
    ["data-include", "data-include-format", "data-include-replace", "data-include-id", "oninclude"].forEach(function (attr) {
      return el.removeAttribute(attr);
    });
  }

  function run(conf, doc, cb) {
    var _this = this;

    var promisesToInclude = Array.from(doc.querySelectorAll("[data-include]")).map(function () {
      var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(el) {
        var url, id, response, text, msg;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                url = el.dataset.include;

                if (url) {
                  _context.next = 3;
                  break;
                }

                return _context.abrupt("return");

              case 3:
                id = "include-" + String(Math.random()).substr(2);

                el.dataset.includeId = id;
                _context.prev = 5;
                _context.next = 8;
                return fetch(url);

              case 8:
                response = _context.sent;
                _context.next = 11;
                return response.text();

              case 11:
                text = _context.sent;

                processResponse(text, id, url);
                _context.next = 20;
                break;

              case 15:
                _context.prev = 15;
                _context.t0 = _context["catch"](5);
                msg = "data-include failed: " + url + " (" + _context.t0.message + "). See console for details.";

                console.error("data-include failed for element: ", el, _context.t0);
                (0, _pubsubhub.pub)("error", msg);

              case 20:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, _this, [[5, 15]]);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
    Promise.all(promisesToInclude).then(cb);
  }
});
//# sourceMappingURL=data-include.js.map