"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var request = require("request");
var config_1 = require("../config");
var HelixCtrl = (function () {
    function HelixCtrl(router) {
        router.route('/helix/list').get(this.list);
        router.route('/helix/*').all(this.proxy);
    }
    HelixCtrl.prototype.proxy = function (req, res) {
        var url = req.originalUrl.replace(HelixCtrl.ROUTE_PREFIX, '');
        var helixKey = url.split('/')[1];
        var segments = helixKey.split('.');
        var group = segments[0];
        segments.shift();
        var name = segments.join('.');
        var user = req.session.username;
        var method = req.method.toLowerCase();
        if (method != 'get' && !req.session.isAdmin) {
            res.status(403).send('Forbidden');
            return;
        }
        var apiPrefix = null;
        if (config_1.HELIX_ENDPOINTS[group]) {
            config_1.HELIX_ENDPOINTS[group].forEach(function (section) {
                if (section[name]) {
                    apiPrefix = section[name];
                }
            });
        }
        if (apiPrefix) {
            var realUrl = apiPrefix + url.replace("/" + helixKey, '');
            var options = {
                url: realUrl,
                json: req.body,
                headers: {
                    'Helix-User': user
                }
            };
            request[method](options, function (error, response, body) {
                if (error) {
                    res.status(500).send(error);
                }
                else {
                    res.status(response.statusCode).send(body);
                }
            });
        }
        else {
            res.status(404).send('Not found');
        }
    };
    HelixCtrl.prototype.list = function (req, res) {
        res.json(config_1.HELIX_ENDPOINTS);
    };
    HelixCtrl.ROUTE_PREFIX = '/api/helix';
    return HelixCtrl;
}());
exports.HelixCtrl = HelixCtrl;
//# sourceMappingURL=helix.js.map
