"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
/*
 * Copyright (c) 2020, salesforce.com, inc.
 * All rights reserved.
 * Licensed under the BSD 3-Clause license.
 * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
 */
const fs = require("fs");
const promises_1 = require("node:fs/promises");
const path = require("path");
const utils_1 = require("../utils");
const baseGenerator_1 = require("./baseGenerator");
const i18n_1 = require("../i18n");
const VALID_TEMPLATES = ['RecordPage', 'AppPage', 'HomePage'];
const MAX_SECONDARY_FIELDS = 11;
class FlexipageGenerator extends baseGenerator_1.BaseGenerator {
    constructor(options) {
        super(options);
    }
    validateOptions() {
        var _a, _b;
        utils_1.CreateUtil.checkInputs(this.options.flexipagename);
        utils_1.CreateUtil.checkInputs(this.options.template);
        if (!VALID_TEMPLATES.includes(this.options.template)) {
            throw new Error(i18n_1.nls.localize('InvalidFlexipageTemplate', [
                this.options.template,
                VALID_TEMPLATES.join(', '),
            ]));
        }
        if (this.options.template === 'RecordPage' && !this.options.entityName) {
            throw new Error(i18n_1.nls.localize('RecordPageRequiresEntityName'));
        }
        // Validate secondary fields limit (dynamicHighlights supports max 11 secondary fields)
        const secondaryFieldsCount = (_b = (_a = this.options.secondaryFields) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
        if (secondaryFieldsCount > MAX_SECONDARY_FIELDS) {
            throw new Error(i18n_1.nls.localize('TooManySecondaryFields', [
                secondaryFieldsCount.toString(),
                MAX_SECONDARY_FIELDS.toString(),
            ]));
        }
        // Ensure output directory includes 'flexipages' folder
        if (!this.options.internal && !this.outputdir.includes('flexipages')) {
            this.outputdir = path.join(this.outputdir, 'flexipages');
        }
    }
    generate() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { template, flexipagename, masterlabel, description, entityName, primaryField, secondaryFields = [], detailFields = [], flexipageTemplatesGitRepo, forceLoadingRemoteRepo, } = this.options;
            // Set up custom templates if provided
            let customTemplatesRootPath;
            if (flexipageTemplatesGitRepo) {
                customTemplatesRootPath = yield (0, baseGenerator_1.setCustomTemplatesRootPathOrGitRepo)(flexipageTemplatesGitRepo, forceLoadingRemoteRepo);
            }
            // Determine template root path
            let templateRootPath;
            if (customTemplatesRootPath) {
                templateRootPath = path.join(customTemplatesRootPath, 'flexipage', template);
                if (!fs.existsSync(templateRootPath)) {
                    throw new Error(i18n_1.nls.localize('MissingFlexipageTemplate', [
                        template,
                        customTemplatesRootPath,
                    ]));
                }
            }
            else {
                // Use built-in templates
                this.sourceRootWithPartialPath('flexipage');
                templateRootPath = this.templatePath(template);
            }
            // Prepare EJS template variables
            const templateVars = {
                flexipagename,
                masterlabel: masterlabel || flexipagename,
                description: description || '',
                apiVersion: this.apiversion,
                entityName: entityName || '',
                primaryField: primaryField || '',
                secondaryFields: Array.isArray(secondaryFields) ? secondaryFields : [],
                detailFields: Array.isArray(detailFields) ? detailFields : [],
            };
            // Recursively process template directory
            yield this.generateFlexipageFromTemplate(templateRootPath, this.outputdir, templateVars);
        });
    }
    /**
     * Recursively process template directory and generate files
     */
    generateFlexipageFromTemplate(sourceDir, destDir, templateVars) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const entries = yield (0, promises_1.readdir)(sourceDir, { withFileTypes: true });
            for (const entry of entries) {
                const sourcePath = path.join(sourceDir, entry.name);
                let destName = entry.name;
                // Replace _flexipage placeholder with actual flexipage name
                if (destName.includes('_flexipage')) {
                    destName = destName.replace(/_flexipage/g, templateVars.flexipagename);
                }
                const destPath = path.join(destDir, destName);
                if (entry.isDirectory()) {
                    // Recursively process subdirectories
                    yield this.generateFlexipageFromTemplate(sourcePath, destPath, templateVars);
                }
                else if (entry.isFile() && this.isTemplateFile(entry.name)) {
                    // Render template files only (skip non-template files)
                    yield this.render(sourcePath, destPath, templateVars);
                }
            }
        });
    }
    /**
     * Check if file should be rendered as EJS template
     */
    isTemplateFile(filename) {
        return filename.endsWith('.flexipage-meta.xml');
    }
}
exports.default = FlexipageGenerator;
//# sourceMappingURL=flexipageGenerator.js.map