import { consoleF1 } from "./utils/define"
console.log = (msg) => {consoleF1.silly(msg) };
console.info = (msg) => {consoleF1.info(msg) };
console.error = (msg) => {consoleF1.error(msg)};
console.warn = (msg) => {consoleF1.warn(msg)};
console.trace = (msg) => {consoleF1.trace(msg)};
import debug from 'debug';
import reload from 'reload';
import App from './app';

debug('ts-express:server');
const port = Number.parseInt(process.env.PORT || '3000');
if (Number.isNaN(port)) {
  console.error('PORT must be a number');
  process.exit(1);
}

// Reload code here
reload(App).then(function (reloadReturned) {
  // reloadReturned is documented in the returns API in the README

  // Reload started, start web server
  const server = App.listen(port, () => {
    console.info(`Serveur disponible à http://localhost:${port}`);
  });

  function onListening(): void {
    let addr = server.address();
    let bind = (typeof addr === 'string') ? `pipe ${addr}` :
      (addr ? `port ${addr.port}` : ``);
    debug(`Listening on ${bind}`);
  }
  
  server.on('error', onError);
  server.on('listening', onListening);
  //server.on("request", onRequest);
  
}).catch(function (err) {
  console.error('Reload could not start, could not start server/sample app', err)
})


function onRequest(request:Request, response:Response){
  console.trace(`${request.method} ${request.url} ${response.status}`);

}

function onError(error: NodeJS.ErrnoException) {
  if (error.syscall !== 'listen') throw error;
  let bind = (typeof port === 'string') ? 'Pipe ' + port : 'Port ' + port;
  switch (error.code) {
    case 'EACCES':
      console.error(`${bind} requires elevated privileges`);
      process.exit(1);
    case 'EADDRINUSE':
      console.error(`${bind} is already in use`);
      process.exit(1);
    default:
      console.error(`${error.code} - ${error.message}`);
      throw error;
  }
}
