"use strict";
/** @format */
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 });
var core_1 = require("@serverless-devs/core");
var utils_1 = require("../utils");
var js_yaml_1 = __importDefault(require("js-yaml"));
var path_1 = __importDefault(require("path"));
var os_1 = __importDefault(require("os"));
var fs_1 = __importDefault(require("fs"));
var CliManager = /** @class */ (function () {
    function CliManager(inputs) {
        this.inputs = inputs;
    }
    CliManager.prototype.getTempCommandStr = function (commands, length) {
        var commandsLength = commands.length;
        var tempArray = new Array(length - commandsLength).fill(' ');
        return "" + commands + tempArray.join('') + " : ";
    };
    CliManager.prototype.init = function () {
        return __awaiter(this, void 0, void 0, function () {
            var result, _a, component, command, access, props, credentials, accessFile, accessFileInfo, e_1, componentInstance, docResult, componentPathYaml, publishYamlInfor, tempLength, item, item, e_2, tempProp, outResult, e_3, e_4;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        result = '';
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 20, , 21]);
                        _a = this.inputs, component = _a.component, command = _a.command, access = _a.access, props = _a.props;
                        credentials = {};
                        _b.label = 2;
                    case 2:
                        _b.trys.push([2, 5, , 6]);
                        accessFile = path_1.default.join(os_1.default.homedir(), '.s', 'access.yaml');
                        accessFileInfo = js_yaml_1.default.load(fs_1.default.readFileSync(accessFile, 'utf8') || '{}');
                        if (!accessFileInfo[access]) return [3 /*break*/, 4];
                        return [4 /*yield*/, core_1.getCredential(access)];
                    case 3:
                        credentials = _b.sent();
                        _b.label = 4;
                    case 4: return [3 /*break*/, 6];
                    case 5:
                        e_1 = _b.sent();
                        credentials = {};
                        return [3 /*break*/, 6];
                    case 6: return [4 /*yield*/, core_1.loadComponent(component, null, { access: access })];
                    case 7:
                        componentInstance = _b.sent();
                        if (!componentInstance) return [3 /*break*/, 19];
                        if (!command) {
                            if (componentInstance['index']) {
                                command = 'index';
                            }
                            else {
                                command = 'cli-help-options';
                            }
                        }
                        if (!(command === 'cli-help-options')) return [3 /*break*/, 13];
                        if (!(componentInstance.__doc && componentInstance.__doc().length > 10)) return [3 /*break*/, 8];
                        docResult = componentInstance.__doc();
                        console.log("" + docResult);
                        return [3 /*break*/, 12];
                    case 8:
                        _b.trys.push([8, 11, , 12]);
                        componentPathYaml = path_1.default.join(componentInstance.__path, 'publish.yml');
                        return [4 /*yield*/, fs_1.default.existsSync(componentPathYaml)];
                    case 9:
                        if (!(_b.sent())) {
                            componentPathYaml = path_1.default.join(componentInstance.__path, 'publish.yaml');
                        }
                        return [4 /*yield*/, js_yaml_1.default.load(fs_1.default.readFileSync(componentPathYaml, 'utf8'))];
                    case 10:
                        publishYamlInfor = _b.sent();
                        console.log("\n  " + publishYamlInfor['Name'] + "@" + publishYamlInfor['Version'] + ": " + publishYamlInfor['Description'] + "\n");
                        tempLength = 0;
                        if (publishYamlInfor['Commands']) {
                            for (item in publishYamlInfor['Commands']) {
                                if (item.length > tempLength) {
                                    tempLength = item.length;
                                }
                            }
                            for (item in publishYamlInfor['Commands']) {
                                console.log("    " + this.getTempCommandStr(item, tempLength) + " " + publishYamlInfor['Commands'][item]);
                            }
                            console.log("\n  " + (publishYamlInfor['HomePage'] ? '🧭 More information: ' + publishYamlInfor['HomePage'] + '\n' : ''));
                        }
                        return [3 /*break*/, 12];
                    case 11:
                        e_2 = _b.sent();
                        utils_1.logger.error('Help information could not be found');
                        return [3 /*break*/, 12];
                    case 12: return [2 /*return*/, 'help'];
                    case 13:
                        if (!componentInstance[command]) return [3 /*break*/, 18];
                        tempProp = {};
                        try {
                            tempProp = JSON.parse(props || '{}');
                        }
                        catch (e) {
                            throw new Error('-p/--prop parameter format error');
                        }
                        _b.label = 14;
                    case 14:
                        _b.trys.push([14, 16, , 17]);
                        return [4 /*yield*/, componentInstance[command]({
                                props: tempProp,
                                Properties: tempProp,
                                Credentials: credentials,
                                credentials: credentials,
                                appName: 'default',
                                Project: {
                                    ProjectName: 'default',
                                    projectName: 'default',
                                    component: component,
                                    Component: component,
                                    provider: undefined,
                                    Provider: undefined,
                                    accessAlias: access || 'default',
                                    AccessAlias: access || 'default',
                                },
                                project: {
                                    component: '',
                                    access: access || 'default',
                                    projectName: '',
                                },
                                command: command,
                                Command: command,
                                args: process.env.temp_params,
                                argsObj: process['temp_params'],
                                Args: process.env.temp_params,
                                ArgsObj: process['temp_params'],
                                path: {
                                    configPath: '',
                                },
                                Path: {
                                    ConfigPath: '',
                                },
                            })];
                    case 15:
                        result =
                            (_b.sent()) || {};
                        outResult = js_yaml_1.default.dump(JSON.parse(JSON.stringify(result)));
                        utils_1.logger.success(Object.keys(result).length === 0 ? "End of method: " + command : outResult);
                        return [3 /*break*/, 17];
                    case 16:
                        e_3 = _b.sent();
                        utils_1.logger.error("Failed to execute:\n\n  \u274C Message: " + e_3.message + "\n  \uD83E\uDDED You can get help for this component by [s cli " + component + " -h]\n  \uD83D\uDE08 If you have questions, please tell us: https://github.com/Serverless-Devs/Serverless-Devs/issues\n");
                        process.exit(-1);
                        return [3 /*break*/, 17];
                    case 17: return [3 /*break*/, 19];
                    case 18:
                        utils_1.logger.error("Failed to execute:\n\n  \u274C Message: Component " + component + " does not include [" + command + "] method\n  \uD83E\uDDED You can get help for this component by [s cli " + component + " -h]\n  \uD83D\uDE08 If you have questions, please tell us: https://github.com/Serverless-Devs/Serverless-Devs/issues\n");
                        process.exit(-1);
                        _b.label = 19;
                    case 19: return [3 /*break*/, 21];
                    case 20:
                        e_4 = _b.sent();
                        utils_1.logger.error("Failed to execute:\n\n  \u274C Message: " + e_4.message + "\n  \uD83E\uDDED You can get more component on: https://github.com/Serverless-Devs/package-awesome\n  \uD83D\uDE08 If you have questions, please tell us: https://github.com/Serverless-Devs/Serverless-Devs/issues\n");
                        process.exit(-1);
                        return [3 /*break*/, 21];
                    case 21: return [2 /*return*/, result];
                }
            });
        });
    };
    return CliManager;
}());
exports.default = CliManager;
//# sourceMappingURL=data:application/json;base64, 