"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resultsToString = exports.mergeResults = exports.renderPageToHtml = void 0;
const zen_observable_1 = __importDefault(require("zen-observable"));
const renderPageToHtml = (page, req, res, renderMode) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const { renderOpts, html: htmlResult } = yield page.renderReqToHTML(req, res, renderMode);
    let html = undefined;
    if (typeof htmlResult === "string") {
        html = htmlResult;
    }
    else {
        if (htmlResult) {
            html = yield ((_a = htmlResult.toUnchunkedString) === null || _a === void 0 ? void 0 : _a.call(htmlResult));
            if (!html) {
                try {
                    html = yield resultsToString([htmlResult]);
                }
                catch (e) {
                    console.log("html could not be rendered using resultsToString()");
                }
            }
        }
    }
    if (!html) {
        console.log("html is empty, falling back to using page's rendering function for html");
        html = renderOpts.isNotFound
            ? ""
            : (yield page.renderReqToHTML(req, res));
    }
    return { html, renderOpts };
});
exports.renderPageToHtml = renderPageToHtml;
function mergeResults(results) {
    return zen_observable_1.default.prototype.concat.call(...results);
}
exports.mergeResults = mergeResults;
function resultsToString(results) {
    return __awaiter(this, void 0, void 0, function* () {
        const chunks = [];
        yield mergeResults(results).forEach((chunk) => {
            chunks.push(chunk);
        });
        return chunks.join("");
    });
}
exports.resultsToString = resultsToString;
