"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.emptyFolder = exports.pathExists = exports.initializePath = exports.exists = exports.arraymove = exports.convertTimeFromNanoSecondsToHHMMSS = exports.getDateFormatted = exports.saveJsonFile = exports.readJsonFile = exports.checkFolder = exports.getFilesAsync = exports.isBase64 = exports.escapeHTML = exports.isMetadata = exports.updateStatus = exports.updateResultsAndPercentages = exports.updatePercentages = exports.streamToArrayAsync = void 0;
const Messages = __importStar(require("../helpers/console-messages"));
const Models = __importStar(require("../models/models"));
const jsonFuture = __importStar(require("json-future"));
const path = __importStar(require("path"));
const date_fns_1 = require("date-fns");
const fs_1 = __importStar(require("fs"));
const os_1 = __importDefault(require("os"));
const streamToArrayAsync = async (stream) => new Promise((resolve, reject) => {
    const items = [];
    stream.on('data', (item) => {
        items.push(item);
    });
    stream.on('error', reject);
    stream.on('end', () => {
        resolve(items);
    });
});
exports.streamToArrayAsync = streamToArrayAsync;
const updatePercentages = (results) => {
    results.ambiguousPercentage = (results.ambiguous ? results.ambiguous / results.total * 100 : 0).toFixed(2);
    results.failedPercentage = (results.failed ? results.failed / results.total * 100 : 0).toFixed(2);
    results.undefinedPercentage = (results.undefined ? results.undefined / results.total * 100 : 0).toFixed(2);
    results.passedPercentage = (results.passed ? results.passed / results.total * 100 : 0).toFixed(2);
    results.pendingPercentage = (results.pending ? results.pending / results.total * 100 : 0).toFixed(2);
    results.skippedPercentage = (results.skipped ? results.skipped / results.total * 100 : 0).toFixed(2);
    if ('variousPercentage' in results) {
        results.variousPercentage = (results.various ? results.various / results.total * 100 : 0).toFixed(2);
        return results;
    }
    return results;
};
exports.updatePercentages = updatePercentages;
const updateResultsAndPercentages = (sourceResults, targetResults) => {
    sourceResults.passed += targetResults.passed;
    sourceResults.failed += targetResults.failed;
    sourceResults.skipped += targetResults.skipped;
    sourceResults.pending += targetResults.pending;
    sourceResults.undefined += targetResults.undefined;
    sourceResults.ambiguous += targetResults.ambiguous;
    sourceResults.total += targetResults.total;
    sourceResults.ambiguousPercentage = (sourceResults.ambiguous ? sourceResults.ambiguous / sourceResults.total * 100 : 0).toFixed(2);
    sourceResults.failedPercentage = (sourceResults.failed ? sourceResults.failed / sourceResults.total * 100 : 0).toFixed(2);
    sourceResults.undefinedPercentage = (sourceResults.undefined ? sourceResults.undefined / sourceResults.total * 100 : 0).toFixed(2);
    sourceResults.passedPercentage = (sourceResults.passed ? sourceResults.passed / sourceResults.total * 100 : 0).toFixed(2);
    sourceResults.pendingPercentage = (sourceResults.pending ? sourceResults.pending / sourceResults.total * 100 : 0).toFixed(2);
    sourceResults.skippedPercentage = (sourceResults.skipped ? sourceResults.skipped / sourceResults.total * 100 : 0).toFixed(2);
    return sourceResults;
};
exports.updateResultsAndPercentages = updateResultsAndPercentages;
const updateStatus = (featureResults) => {
    const result = [];
    if (featureResults.scenarios.ambiguous) {
        result.push({ icon: 'fas fa-question-circle ambiguous-color', status: Models.Status.ambiguous });
    }
    if (featureResults.scenarios.pending) {
        result.push({ icon: 'fas fa-question-circle pending-color', status: Models.Status.pending });
    }
    if (featureResults.scenarios.undefined) {
        result.push({ icon: 'fa fa-question-circle undefined-color', status: Models.Status.undefined });
    }
    if (featureResults.scenarios.skipped) {
        result.push({ icon: 'arrow-circle-right skipped-color', status: Models.Status.skipped });
    }
    if (featureResults.scenarios.failed) {
        result.push({ icon: 'exclamation-circle failed-color', status: Models.Status.failed });
    }
    if (featureResults.scenarios.passed) {
        result.push({ icon: 'check-circle passed-color', status: Models.Status.passed });
    }
    return result;
};
exports.updateStatus = updateStatus;
const isMetadata = (metadata) => Array.isArray(metadata)
    ? !metadata.filter(metadataElement => (!('name' in metadataElement) || !('value' in metadataElement))).length
    : false;
exports.isMetadata = isMetadata;
const escapeHTML = (value) => value
    .replace(/&/gu, '&amp;')
    .replace(/</gu, '&lt;')
    .replace(/>/gu, '&gt;');
exports.escapeHTML = escapeHTML;
const isBase64 = (value) => {
    const base64regex = /^(?<firstGroup>[0-9a-zA-Z+/]{4})*(?<secondGroup>(?<thirdGroup>[0-9a-zA-Z+/]{2}==)|(?<fourthGroup>[0-9a-zA-Z+/]{3}=))?$/u;
    return base64regex.test(value);
};
exports.isBase64 = isBase64;
const getFilesAsync = async (dir) => {
    let files = [];
    const getFiles = async (folder) => {
        files = await fs_1.promises.readdir(folder);
        const result = files.map(async (file) => {
            const fileNameAndPath = path.join(folder, file);
            return fs_1.promises.stat(fileNameAndPath).then((stat) => (stat.isDirectory() ? getFiles(fileNameAndPath) : [fileNameAndPath]));
        });
        return Array.prototype.concat(...(await Promise.all(result)));
    };
    return getFiles(dir);
};
exports.getFilesAsync = getFilesAsync;
const checkFolder = (file) => {
    if (typeof file === 'undefined') {
        return false;
    }
    let stats = {};
    try {
        stats = fs_1.default.statSync(file);
    }
    catch (error) {
        throw new Error(Messages.invalidPathProvided(file));
    }
    return stats.isDirectory();
};
exports.checkFolder = checkFolder;
const readJsonFile = async (file, encoding = 'utf8') => {
    const report = await fs_1.promises.readFile(file, { encoding });
    try {
        return jsonFuture.parse(report);
    }
    catch (error) {
        console.log((Messages.invalidJsonProvided(file, error.message)));
    }
    return null;
};
exports.readJsonFile = readJsonFile;
const saveJsonFile = async (filePath, fileName, json) => {
    const fileNameAndPath = path.join(filePath, fileName);
    const jsonString = await jsonFuture.stringifyAsync({ data: json, replacer: null, space: 4 });
    await fs_1.promises.writeFile(fileNameAndPath, jsonString, { encoding: 'utf8' });
    return true;
};
exports.saveJsonFile = saveJsonFile;
const getDateFormatted = (date) => (0, date_fns_1.format)(date, 'yyyy-MM-dd HH:mm:ss');
exports.getDateFormatted = getDateFormatted;
const convertTimeFromNanoSecondsToHHMMSS = (time) => {
    const duration = (0, date_fns_1.intervalToDuration)({ start: 0, end: time / 1000000 });
    const hours = (`${String(duration.hours)}`).padStart(2, '0');
    const minutes = (`${String(duration.minutes)}`).padStart(2, '0');
    const seconds = (`${String(duration.seconds)}`).padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
};
exports.convertTimeFromNanoSecondsToHHMMSS = convertTimeFromNanoSecondsToHHMMSS;
const arraymove = (arr, fromIndex, toIndex) => {
    const element = arr[fromIndex];
    const deleteCountOne = 1;
    arr.splice(fromIndex, deleteCountOne);
    const deleteCountZero = 0;
    arr.splice(toIndex, deleteCountZero, element);
    return arr;
};
exports.arraymove = arraymove;
const exists = (filePath) => {
    return fs_1.default.existsSync(filePath);
};
exports.exists = exists;
const initializePath = (reportPath) => {
    let reportPathFixed = reportPath;
    const resultCheckReportCreationPath = (0, exports.checkFolder)(reportPath);
    if (!resultCheckReportCreationPath && typeof reportPath === 'undefined') {
        const date = (0, date_fns_1.format)(new Date(), 'yyyy-MM-dd__HH-mm-ss');
        reportPathFixed = path.join(os_1.default.tmpdir(), 'cucumber-html-report-generator', date);
        fs_1.default.mkdirSync(reportPathFixed, { recursive: true });
    }
    return reportPathFixed;
};
exports.initializePath = initializePath;
const pathExists = async (folderPath) => {
    return new Promise((resolve) => {
        fs_1.default.access(folderPath, fs_1.default.constants.F_OK, error => {
            resolve(!error);
        });
    });
};
exports.pathExists = pathExists;
const emptyFolder = async (folderPath) => {
    /* istanbul ignore next */
    if (await (0, exports.pathExists)(folderPath)) {
        await fs_1.promises.rm(folderPath, { recursive: true });
    }
    await fs_1.promises.mkdir(folderPath, { recursive: true });
};
exports.emptyFolder = emptyFolder;
//# sourceMappingURL=common-functions.js.map