"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.AddManager = void 0;
var path_1 = __importDefault(require("path"));
var os_1 = __importDefault(require("os"));
var inquirer_1 = __importDefault(require("inquirer"));
var fs_1 = __importDefault(require("fs"));
var js_yaml_1 = __importDefault(require("js-yaml"));
var commander_1 = __importDefault(require("commander"));
var error_1 = require("../../error");
var common_1 = require("../common/common");
var i18n_1 = __importDefault(require("../../utils/i18n"));
var logger_1 = __importDefault(require("../../utils/logger"));
function isEqualArray(rightFormat, inputFormat) {
    if (!(rightFormat || inputFormat)) {
        return false;
    }
    if (rightFormat.length !== inputFormat.length) {
        return false;
    }
    rightFormat.forEach(function (item) {
        if (!inputFormat.includes(item)) {
            return false;
        }
    });
    return true;
}
var AddManager = /** @class */ (function () {
    function AddManager() {
        this.inputProviderAlias = '';
        this.isRightFormat = true;
        this.globalFilePath = path_1.default.join(os_1.default.homedir(), '.s', 'access.yaml');
        this.inputFullData = {};
        this.context = commander_1.default.args;
    }
    AddManager.prototype.init = function (inputProviderAndAlisName, inputSecretCheck) {
        return __awaiter(this, void 0, void 0, function () {
            var inputSecretCheckKeys, providerAccessFormatSecret, _i, inputSecretCheckKeys_1, item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(commander_1.default.args.length > 0)) return [3 /*break*/, 1];
                        throw new error_1.ConfigError('Configuration failed');
                    case 1:
                        if (!inputProviderAndAlisName.Provider) return [3 /*break*/, 2];
                        this.provider = String(inputProviderAndAlisName.Provider).toLocaleLowerCase();
                        this.aliasName = String(inputProviderAndAlisName.AliasName || 'default').toLocaleLowerCase();
                        if (common_1.providerArray.indexOf(this.provider) === -1) {
                            throw new error_1.ConfigError('The cloud vendor[{{provider}}] was not found. [alibaba/aws/azure/baidu/google/huawei/tencent]', { provider: this.provider });
                        }
                        this.inputSecretID = {};
                        inputSecretCheckKeys = Object.keys(inputSecretCheck);
                        providerAccessFormatSecret = common_1.providerAccessFormat[this.provider];
                        if (isEqualArray(providerAccessFormatSecret, inputSecretCheckKeys)) {
                            for (_i = 0, inputSecretCheckKeys_1 = inputSecretCheckKeys; _i < inputSecretCheckKeys_1.length; _i++) {
                                item = inputSecretCheckKeys_1[_i];
                                this.inputSecretID[item] = inputSecretCheck[item];
                            }
                        }
                        else {
                            throw new error_1.ConfigError('Please Input Right Secret Format: [{{providerAccessFormatSecret}}]', {
                                providerAccessFormatSecret: providerAccessFormatSecret,
                            });
                        }
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, this.inputLengthZero()];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [4 /*yield*/, this.checkInputSecretID()];
                    case 5:
                        _a.sent();
                        this.inputProviderAlias = this.provider + "." + (this.aliasName || 'default');
                        this.inputFullData[this.inputProviderAlias] = this.inputSecretID;
                        this.writeData(this.globalFilePath, this.inputFullData);
                        return [2 /*return*/];
                }
            });
        });
    };
    AddManager.prototype.output = function () {
        logger_1.default.log('');
        logger_1.default.info(i18n_1.default.__('  Provider: {{provider}}', { provider: common_1.providerObject[this.provider] + " (" + this.provider + ")" }));
        if (this.aliasName) {
            logger_1.default.info(i18n_1.default.__('    Alias: {{alias}}', { alias: this.aliasName }));
        }
        // eslint-disable-next-line guard-for-in
        for (var item in this.inputSecretID) {
            logger_1.default.info("    " + item + ": " + this.inputSecretID[item]);
        }
        logger_1.default.log('');
    };
    // 用户输入参数为0的时候
    AddManager.prototype.inputLengthZero = function (provider) {
        if (provider === void 0) { provider = undefined; }
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!provider) return [3 /*break*/, 2];
                        return [4 /*yield*/, inquirer_1.default.prompt(common_1.checkProviderList).then(function (answers) {
                                _this.provider = answers.provider;
                            })];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        this.provider = provider.toLocaleLowerCase();
                        _a.label = 3;
                    case 3:
                        if (!common_1.providerArray.includes(this.provider)) {
                            throw new error_1.ConfigError('The cloud vendor[{{provider}}] was not found. [alibaba/aws/azure/baidu/google/huawei/tencent]', { provider: this.provider });
                        }
                        try {
                            Object.keys(common_1.providerCollection).forEach(function (item) {
                                if (item === _this.provider) {
                                    _this.promptList = common_1.providerCollection[item];
                                }
                            });
                            this.promptList.push({
                                type: 'input',
                                message: i18n_1.default.__('Please create alias for key pair. If not, please enter to skip'),
                                name: 'aliasName',
                                default: 'default', // 默认值
                            });
                        }
                        catch (err) {
                            throw new error_1.ConfigError(err.message);
                        }
                        return [4 /*yield*/, inquirer_1.default.prompt(this.promptList).then(function (answers) {
                                _this.inputSecretID = answers;
                            })];
                    case 4:
                        _a.sent();
                        Object.keys(this.inputSecretID).forEach(function (item) {
                            if (item === 'aliasName') {
                                _this.aliasName = _this.inputSecretID[item];
                                delete _this.inputSecretID[item];
                            }
                        });
                        this.inputProviderAlias = this.provider + '.' + this.aliasName || 'default';
                        return [2 /*return*/, this.inputSecretID];
                }
            });
        });
    };
    // 检查用户输入的输入的inputSecretID是否为空值
    AddManager.prototype.checkInputSecretID = function () {
        return __awaiter(this, void 0, void 0, function () {
            var item, isTrue;
            return __generator(this, function (_a) {
                // eslint-disable-next-line guard-for-in
                for (item in this.inputSecretID) {
                    isTrue = String(typeof this.inputSecretID[item]) === 'string';
                    {
                        if (!this.inputSecretID[item] || !isTrue) {
                            throw new error_1.ConfigError('The Provider[{{provider}}]: key[{{key}}] is required.', {
                                provider: common_1.providerObject[this.provider],
                                key: item,
                            });
                        }
                    }
                }
                return [2 /*return*/];
            });
        });
    };
    AddManager.prototype.writeFileWay = function (filePath, text) {
        return __awaiter(this, void 0, void 0, function () {
            var err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.output();
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, fs_1.default.writeFileSync(filePath, js_yaml_1.default.dump(text))];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        err_1 = _a.sent();
                        throw new error_1.ConfigError('Configuration failed');
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    AddManager.prototype.writeData = function (filePath, text) {
        var isExists = fs_1.default.existsSync(filePath);
        // 当前文件不存在
        if (!isExists) {
            this.writeFileWay(filePath, text);
        }
        else {
            var userInformation = js_yaml_1.default.safeLoad(fs_1.default.readFileSync(filePath, 'utf8'));
            // 文件存在，且不为空；
            // eslint-disable-next-line no-eq-null,eqeqeq
            if (userInformation != null) {
                var userProviderAlias = Object.keys(userInformation);
                var isExistProviderAlias = userProviderAlias.includes(this.inputProviderAlias);
                //全局配置是否含有用户输入的provider.alias
                if (isExistProviderAlias) {
                    throw new error_1.ConfigError('Provider + Alias already exists. You can set a different alias or modify it through: {{input}}', { input: "s config update -p " + this.provider + " -a " + (this.aliasName || 'default') });
                }
                else {
                    try {
                        fs_1.default.appendFileSync(filePath, js_yaml_1.default.dump(text));
                        this.output();
                        logger_1.default.success('Configuration successful');
                    }
                    catch (err) {
                        throw new error_1.ConfigError('Configuration failed');
                    }
                }
            }
            else {
                this.writeFileWay(filePath, text);
            }
        }
    };
    return AddManager;
}());
exports.AddManager = AddManager;
//# sourceMappingURL=data:application/json;base64, 