"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
//external imports
const express = require("express");
const https = require("https");
const WebSocket = require("ws");
const fs = require("fs");
const jwt = require("jsonwebtoken");
const url = require("url");
//internal imports
var routes = require('./routes');
var app = require('./config/app');
var logger = require('./logger');
const clientManager_1 = require("./clientManager");
const channelManager_1 = require("./channelManager");
var privateKey = fs.readFileSync('certs/key.pem', 'utf8');
var certificate = fs.readFileSync('certs/cert.pem', 'utf8');
var options = { key: privateKey, cert: certificate, hostname: app.hostname };
const application = express();
const server = https.createServer(options, application);
const wss = new WebSocket.Server({ noServer: true, maxPayload: 250000, host: app.hostname });
application.use(express.json());
application.use('', routes);
let clientManager = new clientManager_1.default();
let channelManager = new channelManager_1.default();
function startServer() {
    wss.on('connection', (ws, request, args) => {
        var data = JSON.parse(args).data;
        logger.accessLog.info(`Client Connected: ${data.user_id}`);
        if (!channelManager.channelExists(data.channel)) {
            channelManager.createChannel(data);
        }
        if (clientManager.clientExists(data.user_id)) {
            var client = clientManager.getClient(data.user_id);
            if (client != null) {
                client.replaceWebSocket(ws);
            }
        }
        else {
            var client = clientManager.addClient(data, ws);
        }
        if (client != null) {
            channelManager.addClientToChannel(client, data.channel);
        }
        ws.send('Hi there, welcome to braid, Measures Web Socket server.\nConnecting all our services!');
    });
    server.on('upgrade', function upgrade(request, socket, head) {
        return __awaiter(this, void 0, void 0, function* () {
            let args;
            try {
                args = yield verifyConnection();
            }
            catch (e) {
                socket.destroy();
                logger.accessLog.info('Connection Terminated');
                return;
            }
            function verifyConnection() {
                return new Promise((resolve, reject) => {
                    var data = url.parse(request.url, true).query;
                    var token = data.token || (app.environment == 'development' ? app.devToken : '');
                    var accepted = true;
                    var result;
                    jwt.verify(token, app.secret, app.signOptions, function (err, decoded) {
                        if (err) {
                            console.log(err);
                            accepted = false;
                        }
                        result = JSON.stringify(decoded);
                        accepted ? resolve(result) : reject('rejected');
                    });
                });
            }
            wss.handleUpgrade(request, socket, head, function done(ws) {
                wss.emit('connection', ws, request, args);
            });
        });
    });
    server.listen(app.port, () => {
        console.log(`Braid v${app.version} is running!\n`);
        logger.accessLog.info(`Braid v${app.version} is running!\n`);
    });
}
startServer();
module.exports = {
    clientManager: clientManager,
    channelManager: channelManager
};
//# sourceMappingURL=server.js.map