"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = exports.app = void 0;
const lodash_1 = __importDefault(require("lodash"));
const http_auth_1 = __importDefault(require("http-auth"));
const http_auth_connect_1 = __importDefault(require("http-auth-connect"));
const body_parser_1 = __importDefault(require("body-parser"));
const compression_1 = __importDefault(require("compression"));
const express_1 = __importDefault(require("express"));
const graceful_fs_1 = require("graceful-fs");
const config_1 = require("./config");
exports.app = express_1.default();
function init() {
    const router = express_1.default.Router();
    // urls beneath /internal are protected
    const internalAuth = http_auth_1.default.basic({
        realm: 'Knotenformular - Intern'
    }, function (username, password, callback) {
        callback(config_1.config.server.internal.active &&
            username === config_1.config.server.internal.user &&
            password === config_1.config.server.internal.password);
    });
    router.use('/internal', http_auth_connect_1.default(internalAuth));
    router.use(body_parser_1.default.json());
    router.use(body_parser_1.default.urlencoded({ extended: true }));
    const adminDir = __dirname + '/../admin';
    const clientDir = __dirname + '/../client';
    const templateDir = __dirname + '/templates';
    const jsTemplateFiles = [
        '/config.js'
    ];
    function usePromise(f) {
        router.use((req, res, next) => {
            f(req, res).then(next).catch(next);
        });
    }
    router.use(compression_1.default());
    async function serveTemplate(mimeType, req, res) {
        const body = await graceful_fs_1.promises.readFile(templateDir + '/' + req.path + '.template', 'utf8');
        res.writeHead(200, { 'Content-Type': mimeType });
        res.end(lodash_1.default.template(body)({ config: config_1.config.client }));
    }
    usePromise(async (req, res) => {
        if (jsTemplateFiles.indexOf(req.path) >= 0) {
            await serveTemplate('application/javascript', req, res);
        }
    });
    router.use('/internal/admin', express_1.default.static(adminDir + '/'));
    router.use('/', express_1.default.static(clientDir + '/'));
    exports.app.use(config_1.config.server.rootPath, router);
}
exports.init = init;
//# sourceMappingURL=app.js.map