"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordCommandHistory = exports.registerVerbose = exports.registerUniversalCommand = exports.registerCustomerCommand = exports.registerExecCommand = exports.registerCommandChecker = exports.createCustomerCommand = exports.getCustomerCommandInfo = exports.getParsedTemplateObj = exports.getCommandDetail = exports.createUniversalCommand = void 0;
var fs_extra_1 = __importDefault(require("fs-extra"));
var os_1 = __importDefault(require("os"));
var js_yaml_1 = __importDefault(require("js-yaml"));
var path_1 = __importDefault(require("path"));
var commander_1 = require("commander");
var core_1 = require("../core");
var specification_1 = require("../specification");
var static_variable_1 = require("../constants/static-variable");
var storage_1 = __importDefault(require("./storage"));
var i18n_1 = __importDefault(require("./i18n"));
var logger_1 = __importDefault(require("./logger"));
var core_2 = require("@serverless-devs/core");
var getSubcommand = specification_1.version.getSubcommand, getServiceConfig = specification_1.version.getServiceConfig;
function createUniversalCommand(command, customerCommandName, description) {
    var _command = new commander_1.Command(command);
    var processArgv = [];
    var params = [];
    var _customerCommandName = customerCommandName;
    var start = false;
    for (var i = 0; i < process.argv.length; i++) {
        if (!start) {
            processArgv.push(process.argv[i]);
        }
        else {
            params.push(process.argv[i]);
        }
        if (process.argv[i] === command) {
            start = true;
        }
    }
    if (params.length !== 0) {
        process.env.temp_params = params.concat(process.env.temp_params).join(' ');
    }
    else {
        params = process.env.temp_params ? process.env.temp_params.split(' ') : [];
    }
    process.argv = processArgv;
    _command.description(description || '').action(function () {
        var template = process.env[static_variable_1.PROCESS_ENV_TEMPLATE_NAME];
        if (template) {
            var commandManager = new core_1.CommandManager(template, command, _customerCommandName, process.env.temp_params);
            commandManager.init();
        }
    });
    return _command;
}
exports.createUniversalCommand = createUniversalCommand;
function getCommandDetail(name, provider, version) {
    return __awaiter(this, void 0, void 0, function () {
        var command_list;
        return __generator(this, function (_a) {
            command_list = [];
            // try {
            //     const lang = (await handlerProfileFile({ read: true, filePath: 'set-config.yml' })).locale || 'en';
            //     const result: any = await axios.get(SERVERLESS_COMMAND_DESC_URL + `?lang=${lang}`, {
            //         params: {
            //             name,
            //             provider,
            //             version,
            //         },
            //     });
            //     if (result.data && result.data.Response) {
            //         const command = result.data.Response.Command || {};
            //         command_list = Object.keys(command).map(key => {
            //             return {
            //                 name: key,
            //                 desc: command[key],
            //             };
            //         });
            //     }
            // } catch (e) {
            //     logger.error(e.message);
            // }
            return [2 /*return*/, command_list];
        });
    });
}
exports.getCommandDetail = getCommandDetail;
function getParsedTemplateObj(templateFile) {
    return __awaiter(this, void 0, void 0, function () {
        var parse, parsedObj, result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    parse = new specification_1.Parse(templateFile);
                    parsedObj = parse.getOriginalParsedObj();
                    return [4 /*yield*/, parse.getRealVariables(parsedObj)];
                case 1:
                    result = _a.sent();
                    return [2 /*return*/, result];
            }
        });
    });
}
exports.getParsedTemplateObj = getParsedTemplateObj;
function getCustomerCommandInfo(parsedTemplateObj) {
    return getSubcommand(parsedTemplateObj);
}
exports.getCustomerCommandInfo = getCustomerCommandInfo;
function createCustomerCommand(templateFile) {
    return __awaiter(this, void 0, void 0, function () {
        var customerCommands, doc, subCommands, commandListPromise, commandListDetail;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    customerCommands = [];
                    return [4 /*yield*/, getParsedTemplateObj(templateFile)];
                case 1:
                    doc = _a.sent();
                    subCommands = getCustomerCommandInfo(doc);
                    commandListPromise = subCommands.map(function (projectName) { return __awaiter(_this, void 0, void 0, function () {
                        var projectDocDetail;
                        return __generator(this, function (_a) {
                            projectDocDetail = getServiceConfig(doc, projectName);
                            return [2 /*return*/, { projectName: projectName, projectDocDetail: projectDocDetail }];
                        });
                    }); });
                    return [4 /*yield*/, Promise.all(commandListPromise)];
                case 2:
                    commandListDetail = _a.sent();
                    commandListDetail.forEach(function (_a) {
                        var projectName = _a.projectName, projectDocDetail = _a.projectDocDetail;
                        var customerCommand = new commander_1.Command(projectName);
                        var customerCommandDescription = '👉 ' + i18n_1.default.__("This is a customer command please use [s " + projectName + " -h]  obtain the documentation");
                        customerCommand.description(customerCommandDescription);
                        var methodName = process.argv[3];
                        if (methodName) {
                            customerCommand.addCommand(createUniversalCommand(methodName, projectName));
                        }
                        customerCommand.option('-h, --help', i18n_1.default.__('Print usage document'));
                        customerCommand.action(function () { return __awaiter(_this, void 0, void 0, function () {
                            var component, componentInstance, docResult, componentPathYaml, publishYamlInfor, e_1;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        component = projectDocDetail.component;
                                        return [4 /*yield*/, core_2.loadComponent(component)];
                                    case 1:
                                        componentInstance = _a.sent();
                                        if (!componentInstance) return [3 /*break*/, 6];
                                        if (!componentInstance.__doc) return [3 /*break*/, 2];
                                        docResult = componentInstance.__doc(projectName);
                                        logger_1.default.info("\n" + docResult);
                                        return [3 /*break*/, 5];
                                    case 2:
                                        _a.trys.push([2, 4, , 5]);
                                        componentPathYaml = path_1.default.join(componentInstance.__path, "publish.yaml");
                                        return [4 /*yield*/, js_yaml_1.default.load(fs_extra_1.default.readFileSync(componentPathYaml, 'utf8'))];
                                    case 3:
                                        publishYamlInfor = _a.sent();
                                        logger_1.default.info("Help Information: \n                    \n" + publishYamlInfor['Name'] + "@" + publishYamlInfor['version'] + ": " + publishYamlInfor['Description'] + "\n\n" + js_yaml_1.default.dump(publishYamlInfor['Commands']) + "\n" + (publishYamlInfor['HomePage'] ? "🛸  More information :" + publishYamlInfor['HomePage'] + "\n" : ""));
                                        return [3 /*break*/, 5];
                                    case 4:
                                        e_1 = _a.sent();
                                        logger_1.default.info('No document set');
                                        return [3 /*break*/, 5];
                                    case 5: return [3 /*break*/, 7];
                                    case 6:
                                        logger_1.default.info('No document set');
                                        _a.label = 7;
                                    case 7: return [2 /*return*/];
                                }
                            });
                        }); });
                        customerCommands.push(customerCommand);
                    });
                    return [2 /*return*/, customerCommands];
            }
        });
    });
}
exports.createCustomerCommand = createCustomerCommand;
function registerCommandChecker(program) {
    program.on('command:*', function (cmds) {
        var commands = program.commands.map(function (command) { return command.name(); });
        if (!commands.includes(cmds[0])) {
            logger_1.default.error("  error: unknown command " + cmds[0]);
            program.help();
        }
    });
}
exports.registerCommandChecker = registerCommandChecker;
function registerExecCommand(system_command, templateFile) {
    return __awaiter(this, void 0, void 0, function () {
        var execCommand, customerCommandDescription, commandName, projectName, universialCommandInstance, customerCommand, universialCommandInstance;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    execCommand = new commander_1.Command('exec');
                    customerCommandDescription = '🚀 ' + i18n_1.default.__("Subcommand execution analysis.");
                    execCommand.description(customerCommandDescription);
                    execCommand.usage("[subcommand] -- [method] [params]");
                    if (!templateFile) return [3 /*break*/, 4];
                    commandName = '';
                    projectName = '';
                    if (!(process.argv[3] === '--')) return [3 /*break*/, 2];
                    commandName = process.argv[4];
                    return [4 /*yield*/, createUniversalCommand(commandName, projectName, '')];
                case 1:
                    universialCommandInstance = _a.sent();
                    execCommand.addCommand(universialCommandInstance);
                    _a.label = 2;
                case 2:
                    if (!(process.argv[4] === '--' && process.argv[5])) return [3 /*break*/, 4];
                    projectName = process.argv[3];
                    commandName = process.argv[5];
                    customerCommand = new commander_1.Command(projectName);
                    return [4 /*yield*/, createUniversalCommand(commandName, projectName, '')];
                case 3:
                    universialCommandInstance = _a.sent();
                    customerCommand.addCommand(universialCommandInstance);
                    execCommand.addCommand(customerCommand);
                    _a.label = 4;
                case 4:
                    system_command.addCommand(execCommand);
                    return [2 /*return*/];
            }
        });
    });
}
exports.registerExecCommand = registerExecCommand;
function registerCustomerCommand(system_command, templateFile) {
    return __awaiter(this, void 0, void 0, function () {
        var customerCommands;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!templateFile) return [3 /*break*/, 2];
                    return [4 /*yield*/, createCustomerCommand(templateFile)];
                case 1:
                    customerCommands = _a.sent();
                    customerCommands.forEach(function (command) {
                        system_command.addCommand(command);
                    });
                    _a.label = 2;
                case 2: return [2 /*return*/];
            }
        });
    });
}
exports.registerCustomerCommand = registerCustomerCommand;
function registerUniversalCommand(system_command, templateFile) {
    return __awaiter(this, void 0, void 0, function () {
        var parsedTemplateObj, customerCommands;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!templateFile) return [3 /*break*/, 2];
                    return [4 /*yield*/, getParsedTemplateObj(templateFile)];
                case 1:
                    parsedTemplateObj = _a.sent();
                    customerCommands = getCustomerCommandInfo(parsedTemplateObj);
                    if (process.argv[2] && !customerCommands.includes(process.argv[2]) && !['-h', '--help'].includes(process.argv[2])) {
                        system_command.addCommand(createUniversalCommand(process.argv[2]));
                    }
                    else if (process.argv[2] &&
                        customerCommands.includes(process.argv[2]) &&
                        process.argv[3] &&
                        !customerCommands.includes(process.argv[3])) {
                        system_command.addCommand(createUniversalCommand(process.argv[3], process.argv[2]));
                    }
                    _a.label = 2;
                case 2: return [2 /*return*/];
            }
        });
    });
}
exports.registerUniversalCommand = registerUniversalCommand;
function registerVerbose(program) {
    if (process.argv.includes('--verbose')) {
        process.env.VERBOSE = program.verbose;
    }
}
exports.registerVerbose = registerVerbose;
function recordCommandHistory(argv) {
    var file = storage_1.default.getHistoryFile();
    fs_extra_1.default.appendFileSync(file, argv.join(',') + os_1.default.EOL);
}
exports.recordCommandHistory = recordCommandHistory;
exports.default = {
    registerCommandChecker: registerCommandChecker,
    recordCommandHistory: recordCommandHistory,
    registerExecCommand: registerExecCommand,
    registerCustomerCommand: registerCustomerCommand,
    registerUniversalCommand: registerUniversalCommand,
};
//# sourceMappingURL=data:application/json;base64, 