var express = require('express');
var app = express();
var mysql      = require('mysql');

// TODO pull out config.js
// TODO set up read-only db user!
var connections = mysql.createPool({
    connectionLimit : 10, //important
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'olympics2016',
    debug    :  false
});


app.get('/teamstandings/', function (req, res, next) {
  connections.query('SELECT * from team_standings ORDER BY points DESC, golds DESC, silvers DESC', function(err, rows, fields) {
    if (err) {next(err); return;}

    res.send(rows);
  });
});

app.get('/countries/', function (req, res, next) {
  connections.query('SELECT * from countries ORDER BY pool ASC, last_olympics_score DESC', function(err, rows, fields) {
    if (err) {next(err); return;}

    var result = {"pools" : []};
    var pool = null;

    for(var i=0; i<rows.length; ++i) {
      var rawRow = rows[i];
      var row = {
        "name" : rawRow.name,
        "flagPath" : rawRow.flag_path,
        "isActive" : rawRow.is_active == 1,
        "lastOlympicsScore" : rawRow.last_olympics_score
      };

      if (pool == null || rawRow.pool != pool.index) {
        if (pool != null)
          result.pools.push(pool);
        pool = {"index":rawRow.pool, "countries":[row]};
      } else {
        pool.countries.push(row);
      }
    }

    result.pools.push(pool);

    res.send(result);
  });
});

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Internal Server Error');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

@@ -58,21 +58,16 @@
 r mysql 
-     
 = requir
@@ -78,16 +78,16 @@
 ysql');%0A
+
 %0A// TODO
@@ -372,16 +372,23 @@
 andings/
+summary
 ', funct
@@ -582,21 +582,762 @@
     
-res.send(rows
+var result = %7Bstandings: %5B%5D%7D%0A    var previousRow = null;%0A%0A    for (var i=0; i%3Crows.length; ++i) %7B%0A      var rawRow = rows%5Bi%5D;%0A      var position;%0A%0A      if (previousRow != null &&%0A          rawRow.points == previousRow.points &&%0A          rawRow.golds == previousRow.golds &&%0A          rawRow.silvers == previousRow.silvers)%0A        position = previousRawRow.position;%0A      else%0A        position = i+1;%0A%0A      var row = %7B%0A        %22position%22 : position,%0A        %22team%22 : rawRow.team,%0A        %22username%22 : rawRow.username,%0A        %22golds%22 : rawRow.golds,%0A        %22silvers%22 : rawRow.silvers,%0A        %22bronzes%22 : rawRow.bronzes,%0A        %22points%22 : rawRow.points%0A      %7D;%0A%0A      result.standings.push(row);%0A      previousRow = row;%0A    %7D%0A%0A    res.send(result
 );%0A 

Include positions in team standings summary