"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HelixCtrl = void 0;
const request = __importStar(require("request"));
const fs_1 = require("fs");
const config_1 = require("../config");
class HelixCtrl {
    constructor(router) {
        router.route('/helix/list').get(this.list);
        router.route('/helix/*').all(this.proxy);
    }
    proxy(req, res) {
        const url = req.originalUrl.replace(HelixCtrl.ROUTE_PREFIX, '');
        const helixKey = url.split('/')[1];
        const segments = helixKey.split('.');
        const group = segments[0];
        segments.shift();
        const name = segments.join('.');
        const user = req.session.username;
        const method = req.method.toLowerCase();
        if (method != 'get' && !req.session.isAdmin) {
            res.status(403).send('Forbidden');
            return;
        }
        let apiPrefix = null;
        if (config_1.HELIX_ENDPOINTS[group]) {
            config_1.HELIX_ENDPOINTS[group].forEach((section) => {
                if (section[name]) {
                    apiPrefix = section[name];
                }
            });
        }
        if (apiPrefix) {
            const realUrl = apiPrefix + url.replace(`/${helixKey}`, '');
            console.log(`helix-rest request url ${realUrl}`);
            const options = {
                url: realUrl,
                json: req.body,
                headers: {
                    'Helix-User': user,
                },
                agentOptions: {
                    rejectUnauthorized: false,
                },
            };
            if (config_1.SSL.cafiles.length > 0) {
                options.agentOptions.ca = (0, fs_1.readFileSync)(config_1.SSL.cafiles[0], {
                    encoding: 'utf-8',
                });
            }
            if (config_1.IDENTITY_TOKEN_SOURCE) {
                options.headers['Identity-Token'] =
                    res.locals.cookie['helixui_identity.token'];
            }
            request[method](options, (error, response, body) => {
                if (error) {
                    res.status((response === null || response === void 0 ? void 0 : response.statusCode) || 500).send(error);
                }
                else if (body === null || body === void 0 ? void 0 : body.error) {
                    res.status((response === null || response === void 0 ? void 0 : response.statusCode) || 500).send(body === null || body === void 0 ? void 0 : body.error);
                }
                else {
                    res.status(response === null || response === void 0 ? void 0 : response.statusCode).send(body);
                }
            });
        }
        else {
            res.status(404).send('Not found');
        }
    }
    list(req, res) {
        try {
            res.json(config_1.HELIX_ENDPOINTS);
        }
        catch (err) {
            console.log('error from helix/list/');
            console.log(err);
        }
    }
}
exports.HelixCtrl = HelixCtrl;
HelixCtrl.ROUTE_PREFIX = '/api/helix';
//# sourceMappingURL=helix.js.map