#!/usr/bin/env node
process.env.NODE_ENV = 'production';
import http from 'http';
import args from 'args';
import app from './app';
import { createSocketServer } from './socket/index';

args.option('port', 'The port on which the app will be running', 3000);
const flags = args.parse(process.argv);
let port: number = flags.port;

app.set('port', port);

let server = http.createServer(app);

createSocketServer(server);

server.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
server.on('error', onError);

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error: NodeJS.ErrnoException): void {
  if (error.syscall !== 'listen') {
    throw error;
  }

  const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}
