"use strict";
/** @format */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InitManager = void 0;
var path_1 = __importDefault(require("path"));
var fs_extra_1 = __importDefault(require("fs-extra"));
var os_1 = __importDefault(require("os"));
var lodash_1 = __importDefault(require("lodash"));
var child_process_1 = require("child_process");
var inquirer = __importStar(require("inquirer"));
var js_yaml_1 = __importDefault(require("js-yaml"));
var core_1 = require("@serverless-devs/core");
var chalk_1 = __importDefault(require("chalk"));
var utils_1 = require("../utils");
var static_variable_1 = require("../constants/static-variable");
var init_config_1 = require("./init-config");
var window_size_1 = __importDefault(require("window-size"));
inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'));
var replaceTemplate = utils_1.common.replaceTemplate, getTemplatekey = utils_1.common.getTemplatekey, replaceFun = utils_1.common.replaceFun;
var getCredentialAliasList = function () {
    var ACCESS_PATH = utils_1.getYamlPath(path_1.default.join(os_1.default.homedir(), '.s'), 'access');
    if (!ACCESS_PATH) {
        return [];
    }
    try {
        var result = js_yaml_1.default.load(fs_extra_1.default.readFileSync(ACCESS_PATH, 'utf8'));
        return Object.keys(result);
    }
    catch (error) {
        return [];
    }
};
var InitManager = /** @class */ (function () {
    function InitManager() {
        this.promps = {};
    }
    InitManager.prototype.initSconfig = function (appPath) {
        return __awaiter(this, void 0, void 0, function () {
            var sPath, sContent, templateKeys, _a, prompsAccess, prompsRest, prompsOption, result, credential;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        sPath = utils_1.getYamlPath(appPath, 's');
                        if (!sPath) return [3 /*break*/, 5];
                        sContent = fs_extra_1.default.readFileSync(sPath, 'utf-8');
                        templateKeys = getTemplatekey(sContent);
                        templateKeys.forEach(function (item) {
                            var name = item.name, desc = item.desc;
                            if (name === 'access') {
                                var credentialAliasList = getCredentialAliasList();
                                if (Array.isArray(credentialAliasList) && credentialAliasList.length > 0) {
                                    _this.promps['access'] = {
                                        type: 'list',
                                        name: 'access',
                                        message: 'please select credential alias',
                                        choices: credentialAliasList,
                                    };
                                }
                                else {
                                    _this.promps['access'] = {
                                        type: 'confirm',
                                        name: 'access',
                                        message: 'create credential?',
                                        default: true,
                                    };
                                }
                            }
                            else {
                                _this.promps[name] = {
                                    type: 'input',
                                    message: "please input " + (desc || name) + ":",
                                    name: name,
                                };
                            }
                        });
                        _a = this.promps, prompsAccess = _a.access, prompsRest = __rest(_a, ["access"]);
                        prompsOption = lodash_1.default.concat(lodash_1.default.values(prompsRest), prompsAccess);
                        return [4 /*yield*/, inquirer.prompt(lodash_1.default.filter(prompsOption, function (item) { return item; }))];
                    case 1:
                        result = _b.sent();
                        if (!(result.access === true)) return [3 /*break*/, 3];
                        return [4 /*yield*/, core_1.setCredential()];
                    case 2:
                        credential = _b.sent();
                        result.access = credential.Alias;
                        return [3 /*break*/, 4];
                    case 3:
                        result.access = typeof result.access === 'string' ? result.access : 'default';
                        _b.label = 4;
                    case 4:
                        sContent = replaceFun(sContent, result);
                        fs_extra_1.default.writeFileSync(sPath, sContent, 'utf-8');
                        _b.label = 5;
                    case 5: return [2 /*return*/, sPath];
                }
            });
        });
    };
    InitManager.prototype.initEnvConfig = function (appPath) {
        return __awaiter(this, void 0, void 0, function () {
            var envExampleFilePath, envConfig, templateKeys, promptOption, result, newEnvConfig;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        envExampleFilePath = path_1.default.resolve(appPath, '.env.example');
                        if (!fs_extra_1.default.existsSync(envExampleFilePath))
                            return [2 /*return*/];
                        envConfig = fs_extra_1.default.readFileSync(envExampleFilePath, 'utf-8');
                        templateKeys = getTemplatekey(envConfig);
                        if (templateKeys.length === 0)
                            return [2 /*return*/];
                        promptOption = templateKeys.map(function (item) {
                            var name = item.name, desc = item.desc;
                            return {
                                type: 'input',
                                message: "please input " + (desc || name) + ":",
                                name: name,
                            };
                        });
                        return [4 /*yield*/, inquirer.prompt(promptOption)];
                    case 1:
                        result = _a.sent();
                        newEnvConfig = replaceFun(envConfig, result);
                        fs_extra_1.default.unlink(envExampleFilePath);
                        fs_extra_1.default.writeFileSync(path_1.default.resolve(appPath, '.env'), newEnvConfig, 'utf-8');
                        return [2 /*return*/];
                }
            });
        });
    };
    InitManager.prototype.assemblySpecialApp = function (appName, _a) {
        var projectName = _a.projectName, appPath = _a.appPath;
        return __awaiter(this, void 0, void 0, function () {
            var packageJsonPath, publishYamlPath;
            return __generator(this, function (_b) {
                if (appName === 'start-component' || appName === 'devsapp/start-component') {
                    packageJsonPath = path_1.default.join(appPath, 'package.json');
                    publishYamlPath = path_1.default.join(appPath, 'publish.yaml');
                    replaceTemplate([packageJsonPath, publishYamlPath], { projectName: projectName });
                }
                return [2 /*return*/];
            });
        });
    };
    InitManager.prototype.executeInit = function (name, dir, downloadurl) {
        return __awaiter(this, void 0, void 0, function () {
            var projectName, _a, registry, appPath, tempObj, baseChildComponent, e_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = dir;
                        if (_a) return [3 /*break*/, 2];
                        return [4 /*yield*/, inquirer.prompt(init_config_1.PROJECT_NAME_INPUT)];
                    case 1:
                        _a = (_b.sent()).projectName;
                        _b.label = 2;
                    case 2:
                        projectName = _a || './';
                        registry = downloadurl ? downloadurl : utils_1.configSet.getConfig('registry') || static_variable_1.DEFAULT_REGIRSTRY;
                        return [4 /*yield*/, core_1.loadApplication({ registry: registry, target: './', source: name, name: projectName })];
                    case 3:
                        appPath = _b.sent();
                        if (!appPath) return [3 /*break*/, 13];
                        return [4 /*yield*/, this.initSconfig(appPath)];
                    case 4:
                        _b.sent();
                        return [4 /*yield*/, this.initEnvConfig(appPath)];
                    case 5:
                        _b.sent();
                        return [4 /*yield*/, this.assemblySpecialApp(name, { projectName: projectName, appPath: appPath })];
                    case 6:
                        _b.sent(); // Set some app template content
                        _b.label = 7;
                    case 7:
                        _b.trys.push([7, 11, , 12]);
                        if (!process.env[appPath + "-post-init"]) return [3 /*break*/, 10];
                        tempObj = JSON.parse(process.env[appPath + "-post-init"]);
                        return [4 /*yield*/, require(path_1.default.join(tempObj['tempPath'], 'hook'))];
                    case 8:
                        baseChildComponent = _b.sent();
                        return [4 /*yield*/, baseChildComponent.postInit(tempObj)];
                    case 9:
                        _b.sent();
                        _b.label = 10;
                    case 10: return [3 /*break*/, 12];
                    case 11:
                        e_1 = _b.sent();
                        return [3 /*break*/, 12];
                    case 12:
                        utils_1.logger.success('\n🏄‍ Thanks for using Serverless-Devs');
                        console.log("\uD83D\uDC49 You could [cd " + appPath + "] and enjoy your serverless journey!");
                        console.log("\uD83E\uDDED If you need help for this example, you can use [s -h] after you enter folder.");
                        console.log('💞 Document ❤ Star：' + chalk_1.default.cyan('https://github.com/Serverless-Devs/Serverless-Devs' + '\n'));
                        _b.label = 13;
                    case 13: return [2 /*return*/];
                }
            });
        });
    };
    InitManager.prototype.gitCloneProject = function (name, dir) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve) {
                        var gitCmd = child_process_1.spawn('git', ['clone', name], {
                            shell: true,
                            cwd: dir ? dir : './',
                            stdio: ['ignore', 'inherit', 'inherit'],
                        });
                        gitCmd.on('close', function (code) {
                            resolve({ code: code });
                        });
                    })];
            });
        });
    };
    InitManager.prototype.init = function (name, dir) {
        return __awaiter(this, void 0, void 0, function () {
            var tempHeight, answers, answerValue, answersTemp, answersTemp, answersTemp;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        console.log('\n🚀 Serverless Awesome: https://github.com/Serverless-Devs/package-awesome\n');
                        if (!!name) return [3 /*break*/, 9];
                        tempHeight = void 0;
                        try {
                            tempHeight = window_size_1.default.height - 1;
                        }
                        catch (e) {
                            tempHeight = 20;
                        }
                        process.env['serverless_devs_temp_height'] = tempHeight < 15 ? '0' : '1';
                        init_config_1.APPLICATION_TEMPLATE[0].pageSize = tempHeight;
                        return [4 /*yield*/, inquirer.prompt(init_config_1.APPLICATION_TEMPLATE)];
                    case 1:
                        answers = _a.sent();
                        answerValue = answers['template'];
                        if (!(answerValue === 'alibaba')) return [3 /*break*/, 3];
                        process.env['serverless_devs_temp_height'] = tempHeight < 34 ? '0' : '1';
                        init_config_1.ALIBABA_APPLICATION_TEMPLATE[0].pageSize = tempHeight;
                        return [4 /*yield*/, inquirer.prompt(init_config_1.ALIBABA_APPLICATION_TEMPLATE)];
                    case 2:
                        answersTemp = _a.sent();
                        answerValue = answersTemp['template'];
                        return [3 /*break*/, 7];
                    case 3:
                        if (!(answerValue === 'aws')) return [3 /*break*/, 5];
                        init_config_1.AWS_APPLICATION_TEMPLATE[0].pageSize = tempHeight;
                        return [4 /*yield*/, inquirer.prompt(init_config_1.AWS_APPLICATION_TEMPLATE)];
                    case 4:
                        answersTemp = _a.sent();
                        answerValue = answersTemp['template'];
                        return [3 /*break*/, 7];
                    case 5:
                        if (!(answerValue === 'tencent')) return [3 /*break*/, 7];
                        init_config_1.TENCENT_APPLICATION_TEMPLATE[0].pageSize = tempHeight;
                        return [4 /*yield*/, inquirer.prompt(init_config_1.TENCENT_APPLICATION_TEMPLATE)];
                    case 6:
                        answersTemp = _a.sent();
                        answerValue = answersTemp['template'];
                        _a.label = 7;
                    case 7:
                        console.log("\n\uD83D\uDE0B Create application command: [s init " + answerValue + "]\n");
                        return [4 /*yield*/, this.executeInit(answerValue, dir)];
                    case 8:
                        _a.sent();
                        return [3 /*break*/, 13];
                    case 9:
                        if (!(name.lastIndexOf('.git') !== -1)) return [3 /*break*/, 11];
                        return [4 /*yield*/, this.gitCloneProject(name, dir)];
                    case 10:
                        _a.sent();
                        return [3 /*break*/, 13];
                    case 11: return [4 /*yield*/, this.executeInit(name, dir)];
                    case 12:
                        _a.sent();
                        _a.label = 13;
                    case 13: return [2 /*return*/];
                }
            });
        });
    };
    return InitManager;
}());
exports.InitManager = InitManager;
//# sourceMappingURL=data:application/json;base64, 