"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var qs = tslib_1.__importStar(require("qs"));
var init_1 = require("../init");
exports.pathToReg = function (path) {
    return new RegExp("^" + path.replace(/{([^}]+)}/g, function () {
        return "([^/]+)";
    }) + "$", 'g');
};
exports.getPathParamsNames = function (path) {
    var params = [];
    path.replace(/{([^}]+)}/g, function (all, param) {
        params.push(param);
        return all;
    });
    return params;
};
exports.concatPath = function () {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    return args
        .map(function (arg) { return (Array.isArray(arg) ? arg.join('/') : arg !== undefined ? arg : ''); })
        .join('/')
        .replace(/[/]{2,}/g, '/');
};
exports.getPathParams = function (pathTpl, path) {
    var pathParamsNames = exports.getPathParamsNames(pathTpl);
    if (pathParamsNames.length) {
        var pathParamsValues_1 = (exports.pathToReg(pathTpl).exec(path) || []).slice(1);
        return pathParamsNames.reduce(function (pre, cur, index) {
            pre[cur] = pathParamsValues_1[index];
            return pre;
        }, {});
    }
    return undefined;
};
exports.getParams = function (req) {
    var headers = req.headers, _a = req.method, method = _a === void 0 ? '' : _a, _b = req.url, u = _b === void 0 ? '' : _b;
    var _c = init_1.X_SM_PATH, smPath = headers[_c], _d = init_1.X_SM_BASEPATH, smBasePath = headers[_d];
    var _e = u.split('?'), url = _e[0], search = _e[1];
    var p = {
        method: method.toUpperCase(),
        url: url,
        path: exports.getPathParams(exports.concatPath(smBasePath, smPath), url),
        query: search ? qs.parse(search) : undefined,
        header: headers
    };
    return p;
};
exports.getReadableDataAsync = function (readble) {
    return new Promise(function (rs, rj) {
        var buffer = new Buffer('');
        readble.on('data', function (data) {
            buffer = Buffer.concat([buffer, typeof data === 'string' ? new Buffer(data) : data]);
        });
        readble.once('end', function () {
            rs(buffer.toString());
        });
        readble.once('error', function (e) {
            rj(e.message);
        });
    });
};
//# sourceMappingURL=utils.js.map