"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const https_1 = __importDefault(require("https"));
const tls_1 = require("tls");
const fillReqUrl_1 = __importDefault(require("./fillReqUrl"));
class HttpsServer {
    constructor(certService) {
        this.certService = certService;
    }
    static create(certService) {
        return __awaiter(this, void 0, void 0, function* () {
            const httpsServer = new HttpsServer(certService);
            yield httpsServer.init();
            return httpsServer;
        });
    }
    setHttpHandler(httpHandler) {
        this.server.on('request', (req, res) => {
            fillReqUrl_1.default(req, 'https');
            // req.headers["x-forwarded-for"] = this.connectHandler.getIP(req.connection.remotePort);
            httpHandler.handle(req, res);
        });
    }
    setUpgradeHandler(upgradeHandler) {
        this.server.on('upgrade', (req, socket, head) => {
            fillReqUrl_1.default(req, 'wss');
            upgradeHandler.handle(req, socket, head);
        });
    }
    listen(port) {
        return __awaiter(this, void 0, void 0, function* () {
            this.server.listen(port, '0.0.0.0');
        });
    }
    init() {
        return __awaiter(this, void 0, void 0, function* () {
            const serverCrt = yield this.certService.getCertificationForHost('internal_https_server');
            this.server = https_1.default.createServer({
                SNICallback: (servername, cb) => {
                    this.certService.getCertificationForHost(servername).then(crt => {
                        const ctx = tls_1.createSecureContext({
                            cert: crt.cert,
                            key: crt.key,
                        });
                        cb(null, ctx);
                    });
                },
                cert: serverCrt.cert,
                key: serverCrt.key,
            });
        });
    }
}
exports.HttpsServer = HttpsServer;
//# sourceMappingURL=https.js.map