"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 });
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.init = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, component, command, aliasName, props, credentials, accessFile, accessFileInfo, e_1, componentInstance, docResult, tempProp, result, outResult, e_2, e_3;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 13, , 14]);
                        _a = this.inputs, component = _a.component, command = _a.command, aliasName = _a.aliasName, props = _a.props;
                        credentials = {};
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 4, , 5]);
                        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[aliasName]) return [3 /*break*/, 3];
                        return [4 /*yield*/, core_1.getCredential(aliasName)];
                    case 2:
                        credentials = _b.sent();
                        _b.label = 3;
                    case 3: return [3 /*break*/, 5];
                    case 4:
                        e_1 = _b.sent();
                        credentials = {};
                        return [3 /*break*/, 5];
                    case 5: return [4 /*yield*/, core_1.loadComponent(component, null, { aliasName: aliasName })];
                    case 6:
                        componentInstance = _b.sent();
                        if (!componentInstance) return [3 /*break*/, 12];
                        if (!command) {
                            if (componentInstance['index']) {
                                command = 'index';
                            }
                            else {
                                command = 'cli-help-options';
                            }
                        }
                        if (command === "cli-help-options") {
                            docResult = componentInstance.__doc();
                            utils_1.logger.info("\n" + docResult);
                            return [2 /*return*/];
                        }
                        if (!componentInstance[command]) return [3 /*break*/, 11];
                        tempProp = {};
                        try {
                            tempProp = JSON.parse(props || '{}');
                        }
                        catch (e) {
                            throw new Error("-p/--prop parameter format error");
                        }
                        _b.label = 7;
                    case 7:
                        _b.trys.push([7, 9, , 10]);
                        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: aliasName || 'default',
                                    AccessAlias: aliasName || 'default'
                                },
                                project: {
                                    component: '',
                                    access: aliasName || 'default',
                                    projectName: ''
                                },
                                command: command,
                                Command: command,
                                args: process.env.temp_params,
                                Args: process.env.temp_params,
                                path: {
                                    configPath: ''
                                },
                                Path: {
                                    ConfigPath: ''
                                }
                            })];
                    case 8:
                        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*/, 10];
                    case 9:
                        e_2 = _b.sent();
                        utils_1.logger.error("Failed to execute:\n\n  \u274C Message: " + e_2.message + "\n  \uD83E\uDDED You can get help for this component by [s " + 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*/, 10];
                    case 10: return [3 /*break*/, 12];
                    case 11:
                        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 " + 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 = 12;
                    case 12: return [3 /*break*/, 14];
                    case 13:
                        e_3 = _b.sent();
                        utils_1.logger.error("Failed to execute:\n\n  \u274C Message: " + e_3.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*/, 14];
                    case 14: return [2 /*return*/];
                }
            });
        });
    };
    return CliManager;
}());
exports.default = CliManager;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2xpLW1hbmFnZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvY2xpL2NsaS1tYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBQUEsOENBQW1FO0FBQ25FLGtDQUFnQztBQUNoQyxvREFBMkI7QUFDM0IsOENBQXdCO0FBQ3hCLDBDQUFvQjtBQUNwQiwwQ0FBb0I7QUFTcEI7SUFHSSxvQkFBWSxNQUFpQjtRQUN6QixJQUFJLENBQUMsTUFBTSxHQUFHLE1BQU0sQ0FBQTtJQUN4QixDQUFDO0lBRUsseUJBQUksR0FBVjs7Ozs7Ozt3QkFFWSxLQUF5QyxJQUFJLENBQUMsTUFBTSxFQUFuRCxTQUFTLGVBQUEsRUFBRSxPQUFPLGFBQUEsRUFBRSxTQUFTLGVBQUEsRUFBRSxLQUFLLFdBQUEsQ0FBZ0I7d0JBR3JELFdBQVcsR0FBRyxFQUFFLENBQUE7Ozs7d0JBRVYsVUFBVSxHQUFHLGNBQUksQ0FBQyxJQUFJLENBQUMsWUFBRSxDQUFDLE9BQU8sRUFBRSxFQUFFLElBQUksRUFBRSxhQUFhLENBQUMsQ0FBQzt3QkFDMUQsY0FBYyxHQUFHLGlCQUFJLENBQUMsSUFBSSxDQUFDLFlBQUUsQ0FBQyxZQUFZLENBQUMsVUFBVSxFQUFFLE1BQU0sQ0FBQyxJQUFJLElBQUksQ0FBQyxDQUFDOzZCQUMxRSxjQUFjLENB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