"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_lib_1 = require("@hediet/cli-lib");
const printCmdHelp_1 = require("./printCmdHelp");
const printCliHelp_1 = require("./printCliHelp");
const showGui_1 = require("./showGui");
function runCliWithDefaultArgs(options) {
    const cmdArgs = options.args || process.argv.slice(2);
    const result = options.cli.parse(cmdArgs);
    function showHelp() {
        console.log();
        if (!result.parsedArgs["help"] && result.errors) {
            for (const e of result.errors.errors) {
                console.error(e.message);
            }
            console.log();
        }
        if (result.selectedCmd) {
            printCmdHelp_1.printCmdHelp({
                cmdName: result.selectedCmd.name,
                appName: options.info.appName,
            }, result.selectedCmd);
        }
        else {
            printCliHelp_1.printCliHelp(options.cli, options.info);
        }
        console.log();
    }
    function run(data) {
        options.dataHandler(data).catch(e => {
            // todo
            console.error(e);
        });
    }
    if (result.parsedArgs["help"]) {
        showHelp();
        return;
    }
    else if (result.parsedArgs["version"]) {
        console.log(`version: ${options.info.version}`);
        return;
    }
    else if (result.parsedArgs["cmd::gui"]) {
        showGui_1.showGui(options.cli);
        return;
    }
    else if (result.parsedArgs["cmd::schema"]) {
        const schema = cli_lib_1.cliToSchema(options.cli);
        const json = cli_lib_1.sSchema.serialize(schema);
        console.log(JSON.stringify(json, undefined, 4));
        return;
    }
    else if (result.parsedArgs["cmd::json-args"]) {
        const jsonStr = result.parsedArgs["cmd::json-args"];
        const json = JSON.parse(jsonStr);
        const cmd = options.cli
            .getSerializer()
            .deserializeTyped(json)
            .unwrap();
        const data = cmd.getData();
        run(data);
        return;
    }
    else if (result.errors) {
        showHelp();
        return;
    }
    if (!result.dataFactory) {
        throw new Error("Error");
    }
    const data = result.dataFactory();
    run(data);
}
exports.runCliWithDefaultArgs = runCliWithDefaultArgs;
//# sourceMappingURL=handleExtendedCmd.js.map