import { glob }  from '../lib/builderator.js';
import logging from '../lib/logging.js';
import path from 'path';

export const description = "Runs the queue server (needs redis).";

export const options = [];

const ACTIVE_QUEUES = {};

export const main = async (opts) => {
  const log = logging.create("/commands/queue.js");
  const queues = await import("../lib/queues.js");

  const files = glob("./queues/*.js");

  for(let file_name of files) {
    log.info(`Loading queue ${file_name}`);

    try {
      const route = await import(`../${file_name}`);

      let base = `${path.basename(file_name, '.js')}`;

      for(let func_name of Object.getOwnPropertyNames(route)) {
        const route_name = `${base}/${func_name}`;

        log.info(`Creating queue for ${file_name}:${func_name} named ${route_name}`);

        const queue = queues.create(route_name);

        queue.process(route[func_name]);
        ACTIVE_QUEUES[route_name] = queue;
      }
    } catch(error) {
      log.error(error, `Failed to load ${file_name}.`);
    }
  }

  log.info("Queues loading, waiting for messages.");

  // see: https://github.com/nodejs/node/issues/35212
  process.on('SIGINT', () => process.exit());
}
