"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = command;
const picocolors_1 = __importDefault(require("picocolors"));
const commander_1 = require("commander");
const conf_1 = require("@lingui/conf");
const api_1 = require("./api");
const path_1 = __importDefault(require("path"));
const normalize_path_1 = __importDefault(require("normalize-path"));
const extractWorkerPool_1 = require("./api/extractWorkerPool");
const resolveWorkersOptions_1 = require("./api/resolveWorkersOptions");
async function command(config, options) {
    options.verbose && console.log("Extracting messages from source files…");
    const catalogs = await (0, api_1.getCatalogs)(config);
    const catalogStats = {};
    let commandSuccess = true;
    let workerPool;
    if (options.workersOptions.poolSize) {
        options.verbose &&
            console.log(`Use worker pool of size ${options.workersOptions.poolSize}`);
        workerPool = (0, extractWorkerPool_1.createExtractWorkerPool)(options.workersOptions);
    }
    try {
        await Promise.all(catalogs.map(async (catalog) => {
            const result = await catalog.makeTemplate(Object.assign(Object.assign({}, options), { orderBy: config.orderBy, workerPool }));
            if (result) {
                catalogStats[(0, normalize_path_1.default)(path_1.default.relative(config.rootDir, catalog.templateFile))] = Object.keys(result).length;
            }
            commandSuccess && (commandSuccess = Boolean(result));
        }));
    }
    finally {
        if (workerPool) {
            await workerPool.terminate(true);
        }
    }
    Object.entries(catalogStats).forEach(([key, value]) => {
        console.log(`Catalog statistics for ${picocolors_1.default.bold(key)}: ${picocolors_1.default.green(value)} messages`);
        console.log();
    });
    return commandSuccess;
}
if (require.main === module) {
    commander_1.program
        .option("--config <path>", "Path to the config file")
        .option("--verbose", "Verbose output")
        .option("--workers <n>", "Number of worker threads to use (default: CPU count - 1, capped at 8). Pass `--workers 1` to disable worker threads and run everything in a single process")
        .parse(process.argv);
    const options = commander_1.program.opts();
    const config = (0, conf_1.getConfig)({
        configPath: options.config,
    });
    const result = command(config, {
        verbose: options.verbose || false,
        workersOptions: (0, resolveWorkersOptions_1.resolveWorkersOptions)(options),
    }).then(() => {
        if (!result)
            process.exit(1);
    });
}
