"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var path = require("path");
var fs = require("fs");
var request = require("request");
var chalk_1 = require("chalk");
var swagger2ts_1 = require("./swagger2ts");
var serve_1 = require("./yapi/serve");
var init_1 = require("./init");
var guard_1 = require("./guard");
var defaultParseConfig = {
    '-l': 'typescript-angularjs',
    '-t': path.join(init_1.pluginsPath, 'typescript-tkit'),
    '-o': path.join(process.cwd(), 'src', 'services')
};
function gen(config, options) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var url, _a, type, swaggerParser, _b, requestConfig, swaggerUrl, yapiTMP, swagger2tsConfig, servicesPath, code, swaggerData, guardConfig, warnings, _c, w_1, errors_1, _d, errors, w, suggestions, res;
        return tslib_1.__generator(this, function (_e) {
            switch (_e.label) {
                case 0:
                    url = config.url, _a = config.type, type = _a === void 0 ? 'swagger' : _a, swaggerParser = config.swaggerParser, _b = config.requestConfig, requestConfig = _b === void 0 ? {} : _b;
                    swaggerUrl = (requestConfig.url = requestConfig.url || url || '');
                    if (!swaggerUrl) {
                        console.log(chalk_1.default.red("[ERROR]: swagger url not specified"));
                        return [2 /*return*/, 1];
                    }
                    if (!swaggerUrl.match(/^http/)) {
                        swaggerUrl = path.join(process.cwd(), swaggerUrl);
                        if (!fs.existsSync(swaggerUrl)) {
                            console.log(chalk_1.default.red("[ERROR]: swagger " + swaggerUrl + " not found"));
                            return [2 /*return*/, 1];
                        }
                    }
                    if (!(type === 'yapi')) return [3 /*break*/, 2];
                    return [4 /*yield*/, serve_1.default(swaggerUrl, config.yapiConfig)];
                case 1:
                    yapiTMP = _e.sent();
                    if ('result' in yapiTMP && yapiTMP.result && !yapiTMP.code) {
                        swaggerUrl = yapiTMP.result;
                    }
                    else {
                        console.log(chalk_1.default.red("[ERROR]: gen failed with: " + yapiTMP.message));
                        return [2 /*return*/, 1];
                    }
                    _e.label = 2;
                case 2:
                    swagger2tsConfig = tslib_1.__assign({}, defaultParseConfig, swaggerParser);
                    servicesPath = swagger2tsConfig['-o'];
                    return [4 /*yield*/, new Promise(function (rs) {
                            var loader = function (cb) {
                                if (swaggerUrl.match(/^http/)) {
                                    request.get(tslib_1.__assign({}, requestConfig, { url: swaggerUrl }), cb);
                                }
                                else {
                                    try {
                                        cb(undefined, { body: JSON.stringify(require(swaggerUrl)) });
                                    }
                                    catch (e) {
                                        cb(e.message, {});
                                    }
                                }
                            };
                            loader(function (err, _a) {
                                var body = _a.body;
                                if (err) {
                                    console.log(chalk_1.default.red("[ERROR]: download swagger json failed with: " + err));
                                    rs(1);
                                }
                                else {
                                    if (!fs.existsSync(servicesPath)) {
                                        fs.mkdirSync(servicesPath);
                                    }
                                    var swaggerFileName = init_1.basePathToFileName(((body && JSON.parse(body).basePath) || init_1.DefaultBasePath) + ".json");
                                    var swaggerPath = path.join(init_1.SmTmpDir, swaggerFileName);
                                    fs.writeFileSync(swaggerPath, body ? JSON.stringify(JSON.parse(body), null, 2) : body, {
                                        encoding: 'utf8'
                                    });
                                    swaggerUrl = swaggerPath;
                                    rs(0);
                                }
                            });
                        })];
                case 3:
                    code = _e.sent();
                    if (code) {
                        return [2 /*return*/, code];
                    }
                    swaggerData = require(swaggerUrl);
                    guardConfig = config.guardConfig || {};
                    warnings = Array();
                    return [4 /*yield*/, guard_1.strictModeGuard(swaggerData, guardConfig)];
                case 4:
                    _c = _e.sent(), w_1 = _c.warnings, errors_1 = _c.errors;
                    warnings.push.apply(warnings, w_1);
                    if (errors_1.length) {
                        console.log(chalk_1.default.red(errors_1.join('\n')));
                        return [2 /*return*/, 1];
                    }
                    return [4 /*yield*/, guard_1.operationIdGuard(swaggerData, guardConfig)];
                case 5:
                    _d = _e.sent(), errors = _d.errors, w = _d.warnings, suggestions = _d.suggestions;
                    warnings.push.apply(warnings, w);
                    if (warnings.length) {
                        console.log(chalk_1.default.yellow(warnings.join('\n')));
                    }
                    fs.writeFileSync(swaggerUrl, JSON.stringify(swaggerData, null, 2), { encoding: 'utf8' });
                    if (errors.length) {
                        console.log(chalk_1.default.red(errors.join('\n')));
                        if (suggestions.length) {
                            console.log(chalk_1.default.green(JSON.stringify(suggestions, undefined, 2)));
                        }
                        return [2 /*return*/, 1];
                    }
                    else {
                        if (suggestions.length) {
                            console.log(chalk_1.default.green(JSON.stringify(suggestions, undefined, 2)));
                        }
                    }
                    return [4 /*yield*/, swagger2ts_1.default(tslib_1.__assign({}, swagger2tsConfig, { '-i': swaggerUrl }), options.clear)];
                case 6:
                    res = _e.sent();
                    if (res.code) {
                        console.log(chalk_1.default.red("[ERROR]: gen failed with: " + res.message));
                        return [2 /*return*/, 1];
                    }
                    else {
                        console.log(chalk_1.default.green("[INFO]: gen success with: " + requestConfig.url));
                    }
                    return [2 /*return*/, 0];
            }
        });
    });
}
exports.default = gen;
//# sourceMappingURL=index.js.map