import 'dotenv/config';
import { spawn } from "child_process";

console.debug = function(){
    if (process.env.debug){
      console.log.apply(console, arguments);
    }
}

import App from './app/App.js';

const modules = [
  {name: 'Config', path:'app/Config.js'},
  {name: 'Db', path:'app/Db.js'},
  {name: 'AccessManager', path:'app/AccessManager.js'},

  {name: 'GameObjectsManager', path:'app/bl/GameObjectsManager.js'},
  {name: 'ScenariosManager', path:'app/bl/ScenariosManager.js'},
  {name: 'GamesManager', path:'app/bl/GamesManager.js'},
  {name: 'UserManager', path:'app/bl/UserManager.js'},

  {name: 'WebServer', path:'app/WebServer.js'},

  {name: 'AssetController', path: 'controllers/AssetController.js'},
  {name: 'GameObjectsController', path:'controllers/api/GameObjectsController.js'},
  {name: 'ScenariosController', path:'controllers/api/ScenariosController.js'},
  {name: 'GamesController', path:'controllers/api/GamesController.js'},
  {name: 'UsersController', path:'controllers/api/UsersController.js'},
]

process.on('uncaughtException', err => {
  console.error(err, 'Uncaught Exception thrown');
}).on('unhandledRejection', (reason, p) => {
  console.error(reason, 'Unhandled Rejection at Promise', p);
});

if (process.env.NODE_ENV == 'development'){
  console.log('Running in development mode');
  process.stdin.resume();
  process.stdin.on('data', async (data) => {
      const input = data.toString().trim();
      if (input === 'r') {
          process.stdin.pause();
          await app.stop();
          console.log('Restarting...');
          spawn(process.argv.shift(), process.argv, {
              cwd: process.cwd(),
              stdio: "inherit"
          });
      }
  });
}

const app = new App();
await app.importModules(modules);
await app.init();

console.log(`Starting...`);
app.start();