"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTestFromDb = exports.getTestsTreeFromDatabase = exports.mergeDatabases = exports.downloadDatabases = exports.prepareUrls = void 0;
const path_1 = __importDefault(require("path"));
const crypto_1 = __importDefault(require("crypto"));
const axios_1 = __importDefault(require("axios"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const chalk_1 = __importDefault(require("chalk"));
const nested_error_stacks_1 = __importDefault(require("nested-error-stacks"));
const static_1 = require("../tests-tree-builder/static");
const commonSqliteUtils = __importStar(require("./common"));
const common_utils_1 = require("../common-utils");
const constants_1 = require("../constants");
__exportStar(require("./common"), exports);
const prepareUrls = (urls, baseUrl) => (0, common_utils_1.isUrl)(baseUrl) ? (0, common_utils_1.normalizeUrls)(urls, baseUrl) : urls;
exports.prepareUrls = prepareUrls;
async function downloadDatabases(dbJsonUrls, opts) {
    const loadDbJsonUrl = async (dbJsonUrl) => {
        if ((0, common_utils_1.isUrl)(dbJsonUrl)) {
            return (0, common_utils_1.fetchFile)(dbJsonUrl);
        }
        const data = await fs_extra_1.default.readJSON(dbJsonUrl);
        return { data };
    };
    const loadDbUrl = (dbUrl, opts) => downloadSingleDatabase(dbUrl, opts);
    return commonSqliteUtils.handleDatabases(dbJsonUrls, { ...opts, loadDbJsonUrl, prepareUrls: exports.prepareUrls, loadDbUrl });
}
exports.downloadDatabases = downloadDatabases;
async function mergeDatabases(srcDbPaths, reportPath) {
    try {
        const mainDatabaseUrls = path_1.default.resolve(reportPath, constants_1.DATABASE_URLS_JSON_NAME);
        const mergedDbPath = path_1.default.resolve(reportPath, constants_1.LOCAL_DATABASE_NAME);
        const mergedDb = new better_sqlite3_1.default(mergedDbPath);
        commonSqliteUtils.mergeTables({ db: mergedDb, dbPaths: srcDbPaths, getExistingTables: (statement) => {
                return statement.all().map((table) => table.name);
            } });
        for (const dbPath of srcDbPaths) {
            await fs_extra_1.default.remove(dbPath);
        }
        await rewriteDatabaseUrls([mergedDbPath], mainDatabaseUrls, reportPath);
        mergedDb.close();
    }
    catch (err) { // eslint-disable-line @typescript-eslint/no-explicit-any
        throw new nested_error_stacks_1.default('Error while merging databases', err);
    }
}
exports.mergeDatabases = mergeDatabases;
function getTestsTreeFromDatabase(toolName, dbPath, baseHost) {
    try {
        const db = new better_sqlite3_1.default(dbPath, { readonly: true, fileMustExist: true });
        const testsTreeBuilder = static_1.StaticTestsTreeBuilder.create({ toolName, baseHost });
        const suitesRows = db.prepare(commonSqliteUtils.selectAllSuitesQuery())
            .raw()
            .all()
            .sort(commonSqliteUtils.compareDatabaseRowsByTimestamp);
        const { tree } = testsTreeBuilder.build(suitesRows);
        db.close();
        return tree;
    }
    catch (err) { // eslint-disable-line @typescript-eslint/no-explicit-any
        throw new nested_error_stacks_1.default('Error while getting data from database', err);
    }
}
exports.getTestsTreeFromDatabase = getTestsTreeFromDatabase;
async function downloadSingleDatabase(dbUrl, { pluginConfig }) {
    if (!(0, common_utils_1.isUrl)(dbUrl)) {
        return path_1.default.resolve(pluginConfig.path, dbUrl);
    }
    const dest = path_1.default.resolve(pluginConfig.path, getUniqueFileNameForLink(dbUrl));
    common_utils_1.logger.log(chalk_1.default.green(`Download ${dbUrl} to ${pluginConfig.path}`));
    const response = await (0, axios_1.default)({
        url: dbUrl,
        responseType: 'stream'
    });
    const writer = fs_extra_1.default.createWriteStream(dest);
    response.data.pipe(writer);
    await new Promise((resolve, reject) => {
        writer.on('finish', resolve);
        writer.on('error', reject);
    });
    return dest;
}
function getUniqueFileNameForLink(link) {
    const fileName = crypto_1.default
        .createHash('sha256')
        .update(link)
        .digest('hex');
    const fileExt = path_1.default.extname(new URL(link).pathname);
    return `${fileName}${fileExt}`;
}
async function rewriteDatabaseUrls(dbPaths, mainDatabaseUrls, reportPath) {
    const dbUrls = dbPaths.map(p => path_1.default.relative(reportPath, p));
    await fs_extra_1.default.writeJson(mainDatabaseUrls, {
        dbUrls,
        jsonUrls: []
    });
}
const getTestFromDb = (dbClient, testResult) => {
    return dbClient.query({
        select: '*',
        where: `${constants_1.DB_COLUMNS.SUITE_PATH} = ? AND ${constants_1.DB_COLUMNS.NAME} = ? AND ${constants_1.DB_COLUMNS.STATUS} = ?`,
        orderBy: constants_1.DB_COLUMNS.TIMESTAMP,
        orderDescending: true,
        limit: 1
    }, JSON.stringify(testResult.testPath), testResult.browserId, constants_1.TestStatus.SKIPPED);
};
exports.getTestFromDb = getTestFromDb;
//# sourceMappingURL=server.js.map