"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.RenderService = exports.Page = void 0;
const next_aws_cloudfront_1 = __importDefault(require("@getjerry/next-aws-cloudfront"));
const etag_1 = require("../lib/etag");
const console_1 = require("../lib/console");
const render_util_1 = require("./utils/render.util");
class Page {
    constructor(json, html) {
        this.json = json;
        this.html = html;
    }
    getHtmlEtag() {
        return etag_1.createETag().update(this.getHtmlBody()).digest();
    }
    getJsonEtag() {
        return etag_1.createETag().update(JSON.stringify(this.json)).digest();
    }
    getHtmlBody() {
        return this.html;
    }
    getJsonBody() {
        return JSON.stringify(this.json);
    }
    getJson() {
        return this.json;
    }
}
exports.Page = Page;
class RenderService {
    constructor(event) {
        this.event = event;
    }
    getPage(pagePath, rewrittenUri) {
        return __awaiter(this, void 0, void 0, function* () {
            console_1.debug(`[render] Page path: ${pagePath}`);
            const page = require(`./${pagePath}`);
            if (!(page === null || page === void 0 ? void 0 : page.getStaticProps)) {
                return;
            }
            const { req, res } = next_aws_cloudfront_1.default(this.event.Records[0].cf, {
                enableHTTPCompression: false,
                rewrittenUri
            });
            const { renderOpts, html } = yield render_util_1.renderPageToHtml(page, req, res, "passthrough");
            console_1.debug(`[render] Rendered HTML: ${html}`);
            console_1.debug(`[render] Rendered options: ${JSON.stringify(renderOpts)}`);
            return new Page(renderOpts.pageData, html);
        });
    }
}
exports.RenderService = RenderService;
