const http = require('http');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const WebSocket = require('ws');
const shortid = require('shortid');
const broadcast = require('./broadcast');

/**
 * Main store of all game rooms
 * Is used as in-memory database
 *
 * Structure:
 * {
 *   [id]: {
 *     players: [],
 *     maxScore: Number,
 *     playing: Boolean,
 *     ended: Boolean
 *   }
 * }
 * @type {Object}
 */
const games = {};

const port = process.env.PORT || 3000;

const app = express()
  .use(bodyParser.urlencoded({ extended: false }))
  .use(express.static(path.join(__dirname, 'public')))
  .set('view engine', 'ejs')
  .set('views', path.join(__dirname, 'views'))
  .get('/', getHome)
  .post('/', createRoom);

const server = http.createServer(app);
const webSocketServer = new WebSocket.Server({ server });

webSocketServer.broadcast = broadcast;

server.listen(port, function onListen() {
  console.log('Server started at port ' + port);
});

/**
 * [GET] / handler
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function getHome(req, res) {
  res.render('index', { games });
}

/**
 * [POST] / handler
 * Creates new game in store and redirects user to new gameroom
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function createRoom(req, res) {
  const id = shortid.generate();
  games[id] = new Game();
  res.redirect('/game/' + id);
}

/**
 * Game object-creator
 * Sets defaults for new game
 */
function Game() {
  this.players = {};
  this.maxScore = 10;
  this.playing = false;
  this.ended = false;
}

@@ -368,10 +368,14 @@
 rs: 
-%5B%5D
+Object
 ,%0A *
@@ -786,16 +786,40 @@
 ateRoom)
+%0A  .get('/:id', getRoom)
 ;%0A%0Aconst
@@ -1532,21 +1532,401 @@
 ect(
-'/game/' + id
+id);%0A%7D%0A%0A/**%0A * %5BGET%5D /:id handler%0A * Renders game room which matches ID in param%0A * @param  %7BObject%7D req Express request object%0A * @param  %7BObject%7D res Express response object%0A */%0Afunction getRoom(req, res) %7B%0A  // Return the user to the homepage when the room is invalid%0A  if (!games%5Breq.params.id%5D) %7B%0A    return res.redirect('/');%0A  %7D%0A%0A  return res.render('room', %7Bgame: games%5Breq.params.id%5D%7D
 );%0A%7D

Add single-room handler