"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 fse = __importStar(require("fs-extra"));
const lodash = __importStar(require("lodash"));
const path = __importStar(require("path"));
const scripts = __importStar(require("./HtmlChartsScriptsFunctions"));
const ConsoleMessages_1 = require("./ConsoleMessages");
const chalk_1 = __importDefault(require("chalk"));
const open_1 = __importDefault(require("open"));
const hmlFunctions = scripts.HtmlScriptsFunctions;
const featureOverviewScriptsTemplate = 'templates/scripts/featureOverviewScripts.tmpl';
const featuresOverviewScriptsTemplate = 'templates/scripts/featuresOverviewScripts.tmpl';
const reportStylesheetTemplate = 'templates/style.css';
const featuresOverviewIndexTemplate = 'templates/components/features-overview/features-overview-index.tmpl';
const featuresOverviewTableTemplate = 'templates/components/features-overview/features-overview-table.tmpl';
const featuresChartsTemplate = 'templates/components/features-overview/features-charts.tmpl';
const featureChartsTemplate = 'templates/components/feature-overview/feature-charts.tmpl';
const featureOverviewIndexTemplate = 'templates/components/feature-overview/feature-overview.index.tmpl';
const scenarioStepsTemplate = 'templates/components/feature-overview/scenario-elements/steps.tmpl';
const scenarioBeforeTemplate = 'templates/components/feature-overview/scenario-elements/before.tmpl';
const scenarioAfterTemplate = 'templates/components/feature-overview/scenario-elements/after.tmpl';
const tagsTemplate = 'templates/components/feature-overview/scenario-elements/tags.tmpl';
const scenarioNameAndResultsTemplate = 'templates/components/feature-overview/scenario-elements/name-and-results.tmpl';
const scenarioResultsTemplate = 'templates/components/feature-overview/scenario-elements/results.tmpl';
const simpleScenarioTemplate = 'templates/components/feature-overview/scenarios/simple-scenario.tmpl';
const outlineScenarioTemplate = 'templates/components/feature-overview/scenarios/outline-scenario.tmpl';
var ScenarioElements;
(function (ScenarioElements) {
    ScenarioElements["Tags"] = "Tags";
    ScenarioElements["NameAndResults"] = "NameAndResults";
    ScenarioElements["Before"] = "Before";
    ScenarioElements["After"] = "After";
    ScenarioElements["Steps"] = "Steps";
    ScenarioElements["Results"] = "Results";
})(ScenarioElements || (ScenarioElements = {}));
class GenerateHtml {
    constructor(suite, userPproperties) {
        this.suite = suite;
        this.scriptsFunctions = new hmlFunctions(this.suite);
        this.userProperties = userPproperties;
        this.featuresOverviewIndex = path.join(this.userProperties.reportPath, 'index.html');
        // lodash.templateSettings.interpolate = /\{\{=(.+?)\}\}/g;
        // lodash.templateSettings.evaluate = /\{\{(.+?)\}\}/g;
    }
    async createHtmlPages() {
        this._createFeaturesOverviewIndexPage();
        await this._createFeatureIndexPages();
        await this.openReportInBrowser();
    }
    async openReportInBrowser() {
        /* istanbul ignore else */
        if (!this.userProperties.disableLog) {
            console.log(chalk_1.default.blue(ConsoleMessages_1.Messages.reportCreatedBegin + this.featuresOverviewIndex + ConsoleMessages_1.Messages.reportCreatedEnd));
        }
        if (this.userProperties.openReportInBrowser) {
            const dir = path.join(this.userProperties.reportPath, 'features');
            const files = fse.readdirSync(dir);
            /* istanbul ignore next */
            if (files.length === 1 && this.userProperties.navigateToFeatureIfThereIsOnlyOne) {
                await open_1.default(path.join(dir, files[0]));
            }
            else {
                await open_1.default(this.featuresOverviewIndex);
            }
        }
    }
    /**
     * Generate the features overview
     *
     * @private
     */
    _createFeaturesOverviewIndexPage() {
        fse.writeFileSync(this.featuresOverviewIndex, this.generateTemplate(featuresOverviewIndexTemplate, {
            featuresOverview: this.generateTemplate(featuresOverviewTableTemplate, {
                showExecutionTime: this.userProperties.showExecutionTime,
                suite: this.suite
            }),
            featuresOverviewChart: this.generateTemplate(featuresChartsTemplate, {
                config: this.userProperties,
                suite: this.suite
            }),
            featuresOverviewScripts: this.generateTemplate(featuresOverviewScriptsTemplate, {
                config: this.userProperties,
                scriptsFunctions: this.scriptsFunctions,
                suite: this.suite
            }),
            projectName: this.userProperties.projectName,
            styles: this.generateTemplate(reportStylesheetTemplate),
            suite: this.suite
        }));
    }
    /**
     * Generate the feature pages
     *
     * @private
     */
    async _createFeatureIndexPages() {
        const featuresPath = path.resolve(this.userProperties.reportPath, 'features/');
        if (!await fse.pathExists(featuresPath)) {
            fse.mkdirSync(featuresPath);
        }
        (this.suite.features).forEach(feature => {
            const featurePage = `${featuresPath}/${feature.id.toString().replace('/', '_')}.html`;
            fse.writeFileSync(featurePage, this.generateTemplate(featureOverviewIndexTemplate, {
                feature,
                featureOverviewScripts: this.generateTemplate(featureOverviewScriptsTemplate, {
                    feature,
                    scriptsFunctions: this.scriptsFunctions,
                    suite: this.suite
                }),
                featureScenariosOverviewChart: this.generateTemplate(featureChartsTemplate, {
                    featureMetadata: feature.metadata
                }),
                scenarioOutlineTemplate: this.generateScenariosTemplate(feature),
                styles: this.generateTemplate(reportStylesheetTemplate),
                suite: this.suite,
                tags: this.generateTemplate(tagsTemplate, {
                    index: feature.id,
                    tags: feature?.tags
                }),
            }));
        });
    }
    generateScenariosTemplate(feature) {
        const scenarioTemplates = this.generateScenarioElements(feature);
        let scenariosTemplates = '';
        const featureElementsLength = feature?.elements?.length;
        for (let scenarioIndex = 0; scenarioIndex < featureElementsLength; scenarioIndex++) {
            const scenario = feature.elements[scenarioIndex];
            const scenarioId = scenario?.id;
            const simpleScenario = this.generateTemplate(simpleScenarioTemplate, {
                isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                scenarioId,
                scenarioIndex,
                scenarioOutline: this.generateTemplate(outlineScenarioTemplate, {
                    config: this.userProperties,
                    isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                    scenario,
                    scenarioId: scenario?.id,
                    scenarioIndex,
                    scenarioTemplates
                }),
                scenarioTemplates
            });
            scenariosTemplates = scenariosTemplates + simpleScenario;
            const scenarioExampleslength = scenario?.examples?.length;
            scenarioIndex += scenarioExampleslength > 0 ? scenarioExampleslength - 1 : 0;
        }
        return scenariosTemplates;
    }
    generateScenarioElements(feature) {
        const scenarioTemplates = new Map();
        const featureElementsLength = feature?.elements?.length;
        for (let scenarioIndex = 0; scenarioIndex < featureElementsLength; scenarioIndex++) {
            const scenario = feature.elements[scenarioIndex];
            const scenarioElementsTemplates = new Map();
            const scenarioTags = this.generateTemplate(tagsTemplate, {
                index: scenario?.id,
                tags: scenario?.tags
            });
            scenarioElementsTemplates.set(ScenarioElements.Tags, scenarioTags);
            const scenarioNameAndResults = this.generateTemplate(scenarioNameAndResultsTemplate, {
                config: this.userProperties,
                scenario,
                scenarioIndex
            });
            scenarioElementsTemplates.set(ScenarioElements.NameAndResults, scenarioNameAndResults);
            const scenarioResults = this.generateTemplate(scenarioResultsTemplate, {
                scenario,
                scenarioIndex
            });
            scenarioElementsTemplates.set(ScenarioElements.Results, scenarioResults);
            const scenarioSteps = this.generateTemplate(scenarioStepsTemplate, {
                config: this.userProperties,
                isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                scenarioIndex,
                steps: scenario.steps
            });
            scenarioElementsTemplates.set(ScenarioElements.Steps, scenarioSteps);
            const scenarioBefore = this.generateTemplate(scenarioBeforeTemplate, {
                config: this.userProperties,
                scenario,
                scenarioIndex,
                steps: this.generateTemplate(scenarioStepsTemplate, {
                    config: this.userProperties,
                    isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                    scenarioIndex,
                    steps: scenario?.before?.steps
                })
            });
            scenarioElementsTemplates.set(ScenarioElements.Before, scenarioBefore);
            const scenarioAfter = this.generateTemplate(scenarioAfterTemplate, {
                config: this.userProperties,
                scenario,
                scenarioIndex,
                steps: this.generateTemplate(scenarioStepsTemplate, {
                    config: this.userProperties,
                    isFirstScenarioOutline: scenario.isFirstScenarioOutline,
                    scenarioIndex,
                    steps: scenario.after?.steps
                })
            });
            scenarioElementsTemplates.set(ScenarioElements.After, scenarioAfter);
            scenarioTemplates.set(scenarioIndex, scenarioElementsTemplates);
        }
        return scenarioTemplates;
    }
    /**
     * Read a template file and return it's content
     *
     * @param {string} fileName
     * @return {*} Content of the file
     * @private
     */
    readTemplateFile(fileName) {
        return fse.readFileSync(path.join(__dirname, '../', fileName), 'utf-8');
    }
    generateTemplate(templateName, parameters) {
        // parameters = [parameters, {"interpolate": /<?=([\s\S]+?)%>/g) ?>}];
        const compiledTemplate = lodash.template(this.readTemplateFile(templateName));
        return compiledTemplate(parameters);
    }
}
exports.GenerateHtml = GenerateHtml;
//# sourceMappingURL=GenerateHtml.js.map