"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var url_1 = require("url");
var common_1 = require("./common");
function redirectHandler(fromPath, toPath) {
    var route = common_1.url.Route.create(fromPath);
    return function (req, res, next) {
        if (req.method !== 'GET') {
            return next();
        }
        var requestUrl = url_1.parse(req.url, true);
        var pathname = requestUrl.pathname;
        if (route.isMatch(pathname)) {
            var params = route.params(pathname);
            var value = typeof toPath === 'function'
                ? toPath({ url: requestUrl, params: params })
                : toPath;
            var url_2 = url_1.parse(value, true);
            var path = url_2.pathname || '';
            var hasQuery = url_2.search || requestUrl.search;
            if (hasQuery) {
                var query = toMergedQuery(url_2, requestUrl);
                path = path + "?" + query;
            }
            return res.redirect(path);
        }
        return next();
    };
}
exports.redirectHandler = redirectHandler;
var toMergedQuery = function () {
    var urls = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        urls[_i] = arguments[_i];
    }
    var merged = urls.reduce(function (acc, url) {
        var query = url.query;
        return tslib_1.__assign({}, acc, query);
    }, {});
    var toQuery = function (key, value) {
        return value ? key + "=" + value : key;
    };
    var query = Object.keys(merged).map(function (key) { return toQuery(key, merged[key]); });
    return query.join('&');
};
//# sourceMappingURL=handler.redirect.js.map