/*
 * Copyright (c) 2022.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import "reflect-metadata";
import init from 'module-alias';

import path from "path";
init({
    base: path.resolve(__dirname, '../')
});


import {buildConnectionOptions} from "typeorm-extension";
import createExpressApp from "./config/http/express";
import createHttpServer from "./config/http/server";

import env from './env';
import createConfig from "./config";

import createSocketServer from "./modules/socket";
import {createApp} from "./app";
import {createConnection} from "typeorm";

//--------------------------------------------------------------------

(async () => {
    const config = createConfig({env});
    const expressApp = await createExpressApp();
    const httpServer = createHttpServer({expressApp});
    const socketServer = createSocketServer({env, httpServer, config});

    function start() {
        config.components.forEach(c => c.start());
        config.aggregators.forEach(a => a.start());

        httpServer.listen(env.port, signalStart);
    }

    function signalStart() {
        console.table([['Port', env.port], ['Environment', env.env]]);
    }

    const connectionOptions = await buildConnectionOptions();
    const connection = await createConnection(connectionOptions);
    if(process.env.NODE_ENV === 'development') {
        await connection.synchronize();
    }

    await createApp({
        config,
        env,
        expressApp,
        httpServer,
        socketServer,
        connection
    });

    start();
})();

