"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Layout = void 0;
const uuid_1 = require("uuid");
const PageSources_1 = require("../Page/PageSources");
const NodeProcessor_1 = require("../html/NodeProcessor");
const logger = __importStar(require("../utils/logger"));
const LAYOUT_PAGE_BODY_VARIABLE = 'content';
class Layout {
    constructor(sourceFilePath, config) {
        this.sourceFilePath = sourceFilePath;
        this.config = config;
        this.includedFiles = new Set([this.sourceFilePath]);
        this.layoutProcessed = '';
        this.layoutPageBodyVariable = '';
        this.layoutPageNavUuid = '';
        this.headTop = [];
        this.headBottom = [];
        this.scriptBottom = [];
        this.layoutUserScriptsAndStyles = [];
        this.generatePromise = undefined;
    }
    shouldRegenerate(filePaths) {
        return filePaths.some(filePath => this.includedFiles.has(filePath));
    }
    generate() {
        return __awaiter(this, void 0, void 0, function* () {
            let triesLeft = 10;
            let numBodyVars;
            let pageSources;
            let nodeProcessor;
            do {
                const fileConfig = Object.assign(Object.assign({}, this.config), { headerIdMap: {} });
                pageSources = new PageSources_1.PageSources();
                this.layoutPageBodyVariable = `{{${(0, uuid_1.v4)()}-${(0, uuid_1.v4)()}}}`;
                const layoutVariables = { [LAYOUT_PAGE_BODY_VARIABLE]: this.layoutPageBodyVariable };
                const { variableProcessor, pluginManager, siteLinkManager } = this.config;
                const nunjucksProcessed = variableProcessor.renderWithSiteVariables(this.sourceFilePath, pageSources, layoutVariables);
                nodeProcessor = new NodeProcessor_1.NodeProcessor(fileConfig, pageSources, variableProcessor, pluginManager, siteLinkManager, this.layoutUserScriptsAndStyles, 'layout');
                // eslint-disable-next-line no-await-in-loop
                this.layoutProcessed = (yield nodeProcessor.process(this.sourceFilePath, nunjucksProcessed.toString(), this.sourceFilePath, layoutVariables));
                this.layoutPageNavUuid = nodeProcessor.pageNavProcessor.getUuid();
                this.layoutProcessed = pluginManager.postRender(nodeProcessor.frontmatter, this.layoutProcessed);
                const pageBodyVarRegex = new RegExp(this.layoutPageBodyVariable, 'g');
                const bodyVarMatch = this.layoutProcessed.match(pageBodyVarRegex);
                numBodyVars = bodyVarMatch ? bodyVarMatch.length : 0;
                triesLeft -= 1;
            } while (triesLeft > 0 && numBodyVars > 1);
            if (triesLeft === 0) {
                logger.error(`Layout ${this.sourceFilePath} uses more than one {{ ${LAYOUT_PAGE_BODY_VARIABLE} }} variable.`);
                return;
            }
            this.headTop = nodeProcessor.headTop;
            this.headBottom = nodeProcessor.headBottom;
            this.scriptBottom = nodeProcessor.scriptBottom;
            pageSources.addAllToSet(this.includedFiles);
            yield this.config.externalManager.generateDependencies(pageSources.getDynamicIncludeSrc(), this.includedFiles, this.layoutUserScriptsAndStyles);
        });
    }
    insertPage(pageContent, pageNav, pageIncludedFiles) {
        this.includedFiles.forEach(filePath => pageIncludedFiles.add(filePath));
        // Use function for .replace, in case string contains special patterns (e.g. $$, $&, $1, ...)
        return this.layoutProcessed
            .replace(this.layoutPageBodyVariable, () => pageContent)
            .replace(this.layoutPageNavUuid, () => pageNav);
    }
    getPageNjkAssets() {
        return {
            headTop: this.headTop,
            headBottom: this.headBottom,
            scriptBottom: this.scriptBottom,
            layoutUserScriptsAndStyles: this.layoutUserScriptsAndStyles,
        };
    }
}
exports.Layout = Layout;
//# sourceMappingURL=Layout.js.map