import mongoose from "mongoose";
import RabbitEventDelegate from "./_infra/RabbitEventDelegate";
import ModelRepositoryMongo from "./_infra/ModelRepositoryMongo";
import SessionRepositoryREST from "./_infra/SessionRepositoryREST";
import RESTServer from "./_ui/RESTServer";
import SocketServer from "./_ui/SocketServer";
import ModelService from "./application/ModelService";
import config from "./config";

// Init database
connectWithRetry();

const modelRepository = new ModelRepositoryMongo();
const sessionRepository = new SessionRepositoryREST();
const modelService = new ModelService(modelRepository, sessionRepository);
const eventDelegate = new RabbitEventDelegate();

eventDelegate.subscribe(modelService);

function connectWithRetry(): Promise<void> {
    return mongoose.connect(config.database, { useUnifiedTopology: true, useNewUrlParser: true })
        .then(() => {
            console.log("Connecting to database : " + config.database );
        });
}

// Create RESTServer
const socketServer = new SocketServer(config.socketPort);

const server = new RESTServer(config.port, modelService);
modelService.addCrossEntropyObserver(socketServer);

server.start();
socketServer.start();
