"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 });
exports.ComponentExeCute = exports.generateSynchronizeComponentExeList = exports.synchronizeExecuteComponentList = void 0;
var fs_1 = __importDefault(require("fs"));
var path_1 = __importDefault(require("path"));
var os_1 = __importDefault(require("os"));
var static_variable_1 = require("../../constants/static-variable");
var specification_1 = require("../../specification");
var utils_1 = require("../../utils");
var hook_1 = require("./hook");
var js_yaml_1 = __importDefault(require("js-yaml"));
var error_1 = require("../../error");
var core_1 = __importDefault(require("../../utils/core"));
var getCredential = core_1.default.getCredential, loadComponent = core_1.default.loadComponent;
var getServiceConfigDetail = specification_1.version.getServiceConfigDetail, getServiceInputs = specification_1.version.getServiceInputs, getServiceActions = specification_1.version.getServiceActions;
var S_COMPONENT_BASE_PATH = path_1.default.join(os_1.default.homedir(), '.s', 'components');
function synchronizeExecuteComponentList(list, index, initData) {
    if (list === void 0) { list = []; }
    if (index === void 0) { index = 0; }
    if (initData === void 0) { initData = {}; }
    return __awaiter(this, void 0, void 0, function () {
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!(index >= 0 && index < list.length)) return [3 /*break*/, 2];
                    return [4 /*yield*/, list[index]().then(function (_a) {
                            var name = _a.name, data = _a.data;
                            return __awaiter(_this, void 0, void 0, function () {
                                return __generator(this, function (_b) {
                                    switch (_b.label) {
                                        case 0:
                                            if (name) {
                                                initData[name] = data;
                                            }
                                            return [4 /*yield*/, synchronizeExecuteComponentList(list, index + 1, initData)];
                                        case 1: return [2 /*return*/, _b.sent()];
                                    }
                                });
                            });
                        })];
                case 1: return [2 /*return*/, _a.sent()];
                case 2: return [2 /*return*/, initData];
            }
        });
    });
}
exports.synchronizeExecuteComponentList = synchronizeExecuteComponentList;
function generateSynchronizeComponentExeList(_a, equipment) {
    var _this = this;
    var list = _a.list, parse = _a.parse, parsedObj = _a.parsedObj, method = _a.method, params = _a.params;
    return list.map(function (projectName) {
        return function () {
            return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                var projectConfig, componentExecute, Output, e_1, tempError, tempErrorAttr;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 3, , 4]);
                            parsedObj.Params = params || '';
                            utils_1.logger.info("Start executing project " + projectName);
                            return [4 /*yield*/, equipment(parse, projectName, parsedObj)];
                        case 1:
                            projectConfig = _a.sent();
                            if (process.env['serverless_devs_temp_access']) {
                                projectConfig.Access = process.env['serverless_devs_temp_access'];
                                projectConfig.access = process.env['serverless_devs_temp_access'];
                            }
                            componentExecute = new ComponentExeCute(projectConfig, method, parsedObj.edition);
                            return [4 /*yield*/, componentExecute.init()];
                        case 2:
                            Output = _a.sent();
                            if (parsedObj.edition) {
                                //  兼容新版规范
                                parsedObj.services[projectName].output = Output;
                            }
                            else {
                                parsedObj[projectName].Output = Output;
                            }
                            utils_1.logger.info("Project " + projectName + " successfully to execute \n\t");
                            resolve({ name: projectName, data: Output });
                            return [3 /*break*/, 4];
                        case 3:
                            e_1 = _a.sent();
                            tempError = JSON.parse(process.env['s-execute-file'] || '{"Error": []}');
                            tempErrorAttr = {};
                            tempErrorAttr[projectName] = e_1.message.includes('e[t] is not a function')
                                ? "Project " + projectName + " does not include [" + method + "] method"
                                : e_1.message;
                            tempError['Error'].push(tempErrorAttr);
                            process.env['s-execute-file'] = JSON.stringify(tempError);
                            (0, error_1.handleError)(e_1, "Project " + projectName + " failed to execute:", false);
                            resolve({});
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            }); });
        };
    });
}
exports.generateSynchronizeComponentExeList = generateSynchronizeComponentExeList;
var ComponentExeCute = /** @class */ (function () {
    function ComponentExeCute(componentConfig, method, version, templateFile) {
        if (version === void 0) { version = '0.0.1'; }
        this.componentConfig = componentConfig;
        this.method = method;
        this.version = version;
        this.templateFile = templateFile;
        if (!fs_1.default.existsSync(S_COMPONENT_BASE_PATH)) {
            fs_1.default.mkdirSync(S_COMPONENT_BASE_PATH);
        }
    }
    ComponentExeCute.prototype.init = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this;
                        return [4 /*yield*/, this.getCredentials()];
                    case 1:
                        _a.credentials = (_b.sent()) || {};
                        return [4 /*yield*/, this.startExecute()];
                    case 2: return [2 /*return*/, _b.sent()];
                }
            });
        });
    };
    ComponentExeCute.prototype.getCredentials = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, access, autoCredential, accessFile, accessFileInfo, accessInfo, _b, e_2;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = getServiceConfigDetail(this.componentConfig), access = _a.access, autoCredential = _a.autoCredential;
                        if (autoCredential === false) {
                            return [2 /*return*/, null];
                        }
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 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*/, 3];
                        return [4 /*yield*/, getCredential(access)];
                    case 2:
                        _b = _c.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        _b = {};
                        _c.label = 4;
                    case 4:
                        accessInfo = _b;
                        this.componentConfig.access = access;
                        return [2 /*return*/, accessInfo];
                    case 5:
                        e_2 = _c.sent();
                        return [3 /*break*/, 6];
                    case 6: return [2 /*return*/, {}];
                }
            });
        });
    };
    ComponentExeCute.prototype.loadExtends = function () {
        var hooks = getServiceActions(this.componentConfig, this.version, { method: this.method });
        var hookExecuteInstance = null;
        if (hooks) {
            hookExecuteInstance = new hook_1.Hook(hooks);
        }
        return hookExecuteInstance;
    };
    ComponentExeCute.prototype.loadPreExtends = function (extend) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!extend) return [3 /*break*/, 2];
                        return [4 /*yield*/, extend.executePreHook()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    ComponentExeCute.prototype.loadAfterExtend = function (extend) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!extend) return [3 /*break*/, 2];
                        return [4 /*yield*/, extend.executeAfterHook()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    ComponentExeCute.prototype.invokeMethod = function (componentInstance, method, data) {
        return __awaiter(this, void 0, void 0, function () {
            var promise;
            var _this = this;
            return __generator(this, function (_a) {
                promise = new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                    var result, e_3;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                return [4 /*yield*/, componentInstance[method](data)];
                            case 1:
                                result = _a.sent();
                                resolve(result);
                                return [3 /*break*/, 3];
                            case 2:
                                e_3 = _a.sent();
                                reject(e_3);
                                return [3 /*break*/, 3];
                            case 3: return [2 /*return*/];
                        }
                    });
                }); });
                return [2 /*return*/, promise];
            });
        });
    };
    ComponentExeCute.prototype.executeCommand = function () {
        return __awaiter(this, void 0, void 0, function () {
            var inputs, name, regirstry, componentClass, data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        inputs = getServiceInputs(this.componentConfig, this.version, {
                            method: this.method,
                            credentials: this.credentials,
                        });
                        name = getServiceConfigDetail(this.componentConfig).name;
                        regirstry = utils_1.configSet.getConfig('registry') || static_variable_1.DEFAULT_REGIRSTRY;
                        return [4 /*yield*/, loadComponent(name, regirstry)];
                    case 1:
                        componentClass = _a.sent();
                        return [4 /*yield*/, this.invokeMethod(componentClass, this.method, inputs)];
                    case 2:
                        data = _a.sent();
                        return [2 /*return*/, data];
                }
            });
        });
    };
    ComponentExeCute.prototype.startExecute = function () {
        return __awaiter(this, void 0, void 0, function () {
            var outData, tempParams, helpArgs, extend, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        outData = {};
                        tempParams = process.env.temp_params || '';
                        helpArgs = tempParams.includes('--help') || tempParams.includes('-h');
                        if (!(process.env['skip-actions'] === 'true' || helpArgs)) return [3 /*break*/, 1];
                        _a = null;
                        return [3 /*break*/, 3];
                    case 1: return [4 /*yield*/, this.loadExtends()];
                    case 2:
                        _a = _b.sent();
                        _b.label = 3;
                    case 3:
                        extend = _a;
                        return [4 /*yield*/, this.loadPreExtends(extend)];
                    case 4:
                        _b.sent();
                        return [4 /*yield*/, this.executeCommand()];
                    case 5:
                        outData = _b.sent();
                        return [4 /*yield*/, this.loadAfterExtend(extend)];
                    case 6:
                        _b.sent();
                        return [2 /*return*/, outData];
                }
            });
        });
    };
    return ComponentExeCute;
}());
exports.ComponentExeCute = ComponentExeCute;
//# sourceMappingURL=data:application/json;base64, 