// Imports
import fig from "figlet";
import http from "http";
import express from "express";
import { INFO, OK, logInfo } from "../util/logging.js";

// Import Core Modules
import buildRoutes from "../routes/router.js";
import buildPostgres from "../database/postgres.js";
import injectSockets from "../sockets/socket-server.js";
import JobManager from "../jobs/JobManager.js";
import buildRabbiteer from "../rabbit/rabbit-workers.js";

// Constants
const title = "QLTR";
const port = process.env.QUALITEER_DEV_PORT ?? 52000;

// Class
export default class Qualiteer {
  constructor(options = {}) {
    for (var k in options) this[k] = options[k];
    this.jobs = JobManager;
    this.port = options.port ?? port;
  }

  async _preinitialize() {
    logInfo(fig.textSync(title, "Cyberlarge"));
    INFO("INIT", "Initializing...");
    this.app = express();
    this.pg = buildPostgres();
    this.server = http.createServer(this.app);
    this.sockets = injectSockets(this.server, this.jobs);
    this.routes = buildRoutes(this.pg, this.sockets);
    this.rabbiteer = buildRabbiteer(this.pg, this.sockets);
    this.app.use(this.routes);
  }

  async _connect() {
    await this.pg.connect();
    // await this.rabbiteer.connect();
  }

  start() {
    const qt = this;
    return new Promise(async function init(res) {
      qt._preinitialize();
      await qt._connect();
      qt.server.listen(qt.port, function onStart() {
        OK("SERVER", `Running on ${qt.port}`);
        res();
      });
    });
  }
}
