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

// Import Core Modules
import expressApp from "./server.js";
import applySockets from "../sockets/handler.js";
import JobManager from "./JobManager.js";
import rabbiteer 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 = new JobManager(options.maxClientJobs ?? 3);
    this.port = options.port ?? port;
  }

  async _preinitialize() {
    logInfo(fig.textSync(title, "Cosmike"));
    INFO("INIT", "Initializing...");
    this.app = expressApp;
    this.server = http.createServer(this.app);
    this.sockets = applySockets(this.server, this.jobs);
    this.rabbiteer = rabbiteer;
  }

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