"use strict";

var _require = require("./errors.js"),
  throwUnimplementedTagType = _require.throwUnimplementedTagType,
  XTScopeParserError = _require.XTScopeParserError;
var _require2 = require("./doc-utils.js"),
  pushArray = _require2.pushArray;
var getResolvedId = require("./get-resolved-id.js");
function moduleRender(part, options) {
  for (var _i2 = 0, _options$modules2 = options.modules; _i2 < _options$modules2.length; _i2++) {
    var _module = _options$modules2[_i2];
    var moduleRendered = _module.render(part, options);
    if (moduleRendered) {
      return moduleRendered;
    }
  }
  return false;
}
function render(options) {
  var baseNullGetter = options.baseNullGetter;
  var compiled = options.compiled,
    scopeManager = options.scopeManager;
  options.nullGetter = function (part, sm) {
    return baseNullGetter(part, sm || scopeManager);
  };
  var errors = [];
  var parts = [];
  for (var i = 0, len = compiled.length; i < len; i++) {
    var part = compiled[i];
    options.index = i;
    options.resolvedId = getResolvedId(part, options);
    var moduleRendered = void 0;
    try {
      moduleRendered = moduleRender(part, options);
    } catch (e) {
      if (e instanceof XTScopeParserError) {
        errors.push(e);
        parts.push(part);
        continue;
      }
      throw e;
    }
    if (moduleRendered) {
      if (moduleRendered.errors) {
        pushArray(errors, moduleRendered.errors);
      }
      parts.push(moduleRendered);
      continue;
    }
    if (part.type === "content" || part.type === "tag") {
      parts.push(part);
      continue;
    }
    throwUnimplementedTagType(part, i);
  }

  // This is done in two steps because for some files, it is possible to #edit-value-backwards
  var totalParts = [];
  for (var _i4 = 0; _i4 < parts.length; _i4++) {
    var value = parts[_i4].value;
    if (value instanceof Array) {
      pushArray(totalParts, value);
    } else if (value) {
      totalParts.push(value);
    }
  }
  return {
    errors: errors,
    parts: totalParts
  };
}
module.exports = render;