"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenerateHtml = void 0;
const CommonFunctions = __importStar(require("../../common-functions/common-functions"));
const ConsoleMessages = __importStar(require("../../helpers/console-messages"));
const fse = __importStar(require("fs-extra"));
const lodash = __importStar(require("lodash"));
const path = __importStar(require("path"));
const scripts = __importStar(require("./html-charts-scripts-functions"));
const fs_1 = __importStar(require("fs"));
const charts_data_1 = require("./charts-data");
const chalk_1 = __importDefault(require("chalk"));
const open_1 = __importDefault(require("open"));
const featureOverviewScriptsTemplate = '/resources/templates/scripts/feature-overview-scripts.tmpl';
const featuresOverviewScriptsTemplate = '/resources/templates/scripts/features-overview-scripts.tmpl';
const reportStylesheetDarkThemeTemplate = '/resources/templates/css/style-dark-theme.css';
const reportStylesheetLightThemeTemplate = '/resources/templates/css/style-light-theme.css';
const featuresOverviewIndexTemplate = '/resources/templates/components/features-overview/features-overview-index.tmpl';
const featuresOverviewTableTemplate = '/resources/templates/components/features-overview/features-overview-table.tmpl';
const featuresChartsTemplate = '/resources/templates/components/features-overview/features-charts.tmpl';
const featureChartsTemplate = '/resources/templates/components/feature-overview/feature-charts.tmpl';
const featureOverviewIndexTemplate = '/resources/templates/components/feature-overview/feature-overview-index.tmpl';
const scenarioStepsTemplate = '/resources/templates/components/feature-overview/scenario-elements/steps.tmpl';
const scenarioBeforeTemplate = '/resources/templates/components/feature-overview/scenario-elements/before.tmpl';
const scenarioAfterTemplate = '/resources/templates/components/feature-overview/scenario-elements/after.tmpl';
const tagsTemplate = '/resources/templates/components/feature-overview/scenario-elements/tags.tmpl';
const scenarioNameAndResultsTemplate = '/resources/templates/components/feature-overview/scenario-elements/name-and-results.tmpl';
const scenarioResultsTemplate = '/resources/templates/components/feature-overview/scenario-elements/results.tmpl';
const simpleScenarioTemplate = '/resources/templates/components/feature-overview/scenarios/simple-scenario.tmpl';
const outlineScenarioTemplate = '/resources/templates/components/feature-overview/scenarios/outline-scenario.tmpl';
const outlineScenarioChildTemplate = '/resources/templates/components/feature-overview/scenarios/outline-scenario-child.tmpl';
const resourcesFolder = '/resources/dependencies/';
class GenerateHtml {
    constructor(suite, reportConfiguration) {
        this.suite = suite;
        this.chartsData = new charts_data_1.ChartsData(this.suite);
        this.reportConfiguration = reportConfiguration;
        this.scriptsFunctions = new scripts.HtmlScriptsFunctions(this.reportConfiguration.theme);
        this.featuresOverviewIndex = path.join(this.reportConfiguration.reportPath, 'index.html');
        const scriptName = path.basename(__filename);
        this.rootFolder = path.join(path.dirname(require.resolve(`./${scriptName}`)), '../../..');
    }
    async createHtmlPages() {
        this.createFeaturesOverviewIndexPage();
        await this.createFeatureIndexPages();
        if (!this.reportConfiguration.useCDN) {
            await this.copyResourcesToTargetFolder();
        }
        await this.openReportInBrowser();
    }
    async openReportInBrowser() {
        /* istanbul ignore else */
        if (this.reportConfiguration.disableLog) {
            console.log(chalk_1.default.blue(ConsoleMessages.reportCreated(this.featuresOverviewIndex)));
        }
        /* istanbul ignore next */
        if (this.reportConfiguration.openReportInBrowser) {
            const dir = path.join(this.reportConfiguration.reportPath, 'features');
            const files = await fs_1.promises.readdir(dir);
            /* istanbul ignore next */
            if (files.length === 1 && this.reportConfiguration.navigateToFeatureIfThereIsOnlyOne) {
                await (0, open_1.default)(path.join(dir, files[0]));
            }
            else {
                const result = await (0, open_1.default)(this.featuresOverviewIndex);
                console.log(result);
            }
        }
    }
    createFeaturesOverviewIndexPage() {
        fs_1.default.writeFileSync(this.featuresOverviewIndex, this.generateTemplate(featuresOverviewIndexTemplate, {
            featuresOverview: this.generateTemplate(featuresOverviewTableTemplate, {
                suite: this.suite
            }),
            config: this.reportConfiguration,
            featuresOverviewChart: this.generateTemplate(featuresChartsTemplate, {
                suite: this.suite
            }),
            featuresOverviewScripts: this.generateTemplate(featuresOverviewScriptsTemplate, {
                config: this.reportConfiguration,
                chartsData: this.chartsData,
                scriptsFunctions: this.scriptsFunctions,
                suite: this.suite
            }),
            projectName: this.suite.reportTitle,
            styles: this.generateTemplate(this.reportConfiguration.overrideStyle ?? (this.reportConfiguration.theme === 'Dark' ? reportStylesheetDarkThemeTemplate : reportStylesheetLightThemeTemplate)),
            customStyle: this.reportConfiguration.customStyle ? this.generateTemplate(this.reportConfiguration.customStyle) : '',
            suite: this.suite
        }));
    }
    async createFeatureIndexPages() {
        const featuresPath = path.resolve(this.reportConfiguration.reportPath, 'features/');
        if (!CommonFunctions.exists(featuresPath)) {
            fs_1.default.mkdirSync(featuresPath);
        }
        await Promise.all(this.suite.features.map(feature => {
            const featurePage = `${featuresPath}/${feature.id.toString().replace('/', '_')}.html`;
            fs_1.default.writeFileSync(featurePage, this.generateTemplate(featureOverviewIndexTemplate, {
                feature,
                featureOverviewScripts: this.generateTemplate(featureOverviewScriptsTemplate, {
                    feature,
                    chartsData: this.chartsData,
                    scriptsFunctions: this.scriptsFunctions,
                    suite: this.suite
                }),
                config: this.reportConfiguration,
                featureScenariosOverviewChart: this.generateTemplate(featureChartsTemplate, {
                    feature
                }),
                scenarioOutlineTemplate: this.generateScenariosTemplate(feature),
                styles: this.generateTemplate(this.reportConfiguration.theme === 'Dark' || this.reportConfiguration.theme !== 'Light' ? reportStylesheetDarkThemeTemplate : reportStylesheetLightThemeTemplate),
                customStyle: this.reportConfiguration.customStyle ? this.generateTemplate(this.reportConfiguration.customStyle) : '',
                suite: this.suite,
                tags: this.generateTemplate(tagsTemplate, {
                    index: feature.id,
                    tags: feature.tags
                }),
            }));
            return feature;
        }));
    }
    generateScenariosTemplate(feature) {
        let scenariosTemplates = '';
        for (let scenarioIndex = 0; scenarioIndex < feature.elements.length; scenarioIndex++) {
            const scenario = (feature.elements)[scenarioIndex];
            const templates = this.getScenarioElementsTemplates(scenario, scenarioIndex);
            if (scenario.isFirstScenarioOutline && scenario.examples?.length) {
                let scenarioOutlineChildsTemplates = '';
                for (let scenarioExamplesIndex = 1; scenarioExamplesIndex < scenario.examples.length; scenarioExamplesIndex++) {
                    const scenarioTemplates = this.getScenarioElementsTemplates((feature.elements)[scenarioIndex + scenarioExamplesIndex], scenarioIndex + scenarioExamplesIndex);
                    scenarioOutlineChildsTemplates += this.generateTemplate(outlineScenarioChildTemplate, {
                        templates: scenarioTemplates,
                        scenarioExamplesIndex,
                        scenarioExamples: (feature.elements)[scenarioIndex].examples
                    });
                }
                const scenarioOutline = this.generateTemplate(outlineScenarioTemplate, {
                    templates,
                    scenarioOutlineChilds: scenarioOutlineChildsTemplates
                });
                scenariosTemplates += scenarioOutline;
                scenarioIndex += scenario.examples.length - 1;
            }
            else {
                const simpleScenario = this.generateTemplate(simpleScenarioTemplate, {
                    templates
                });
                scenariosTemplates += simpleScenario;
            }
        }
        return scenariosTemplates;
    }
    getScenarioElementsTemplates(scenario, scenarioIndex) {
        return {
            config: this.reportConfiguration,
            scenarioIndex,
            scenario,
            scenarioId: scenario.id,
            tags: this.generateTemplate(tagsTemplate, { scenario }),
            nameAndResults: this.generateTemplate(scenarioNameAndResultsTemplate, {
                config: this.reportConfiguration,
                scenario,
                scenarioIndex
            }),
            results: this.generateTemplate(scenarioResultsTemplate, {
                scenario,
                scenarioIndex
            }),
            steps: this.generateTemplate(scenarioStepsTemplate, {
                config: this.reportConfiguration,
                isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                scenarioIndex,
                steps: scenario.steps,
            }),
            before: this.generateTemplate(scenarioBeforeTemplate, {
                config: this.reportConfiguration,
                scenario,
                scenarioIndex,
                steps: this.generateTemplate(scenarioStepsTemplate, {
                    config: this.reportConfiguration,
                    isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                    scenarioIndex,
                    steps: scenario.before?.steps
                })
            }),
            after: this.generateTemplate(scenarioAfterTemplate, {
                config: this.reportConfiguration,
                scenario,
                scenarioIndex,
                steps: this.generateTemplate(scenarioStepsTemplate, {
                    config: this.reportConfiguration,
                    isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                    scenarioIndex,
                    steps: scenario.after?.steps
                })
            })
        };
    }
    readTemplateFile(fileName) {
        return fs_1.default.readFileSync(CommonFunctions.exists(fileName) ? fileName : path.join(this.rootFolder, fileName), 'utf-8');
    }
    generateTemplate(templateName, parameters) {
        const compiledTemplate = lodash.template(this.readTemplateFile(templateName));
        lodash.extend('scriptFunctions', this.scriptsFunctions);
        return compiledTemplate(parameters);
    }
    async copyResourcesToTargetFolder() {
        await fse.copy(path.join(this.rootFolder, resourcesFolder), path.resolve(this.reportConfiguration.reportPath, 'resources'));
    }
}
exports.GenerateHtml = GenerateHtml;
//# sourceMappingURL=generate-html.js.map