<commit_before>var express = require('express'),
    api     = express.Router(),
    _       = require('lodash');
    mongoose = require('mongoose');

var Venues  = require('../models/venue'),
    Users   = require('../models/user'),
    Players = require('../models/player'),
    Event   = require('../models/event'),
    Game    = require('../models/game');

var stats = {};

api.get('/players', function(req, res) {
  stats.players = []
  var pOptions = [
    {
      path : 'event',
      populate: [
        {
          path : 'venue',
          select : 'name day'
        },
        {
          path : 'td',
          select : 'name user',
          populate : {
            path : 'user',
            model : 'User',
            select : 'local.username'
          }
        },
        {
          path : 'games',
          select : 'event number'
        }
      ]
    },
    {
      path : 'players',
      populate : {
        path : 'player',
        select : 'name isTd'
      }
    }
  ];
  Game
    .find({ completed : true })
    .select('-games')
    .populate(pOptions)
    .exec(function(err, games) {
      if (err)
        console.err(err);
      for (var i in games) {
        var players = games[i].players;
        for (var j in players) {
          parsePlayerData(players[j], games[i]);
        }
      }
      res.send(stats.players);
    })

});

function parsePlayerData(record, game) {
  var p = {
    name : record.player.name,
    _id : record.player._id,
    games : [],
    stats : {
      totalGames : 1,
      totalWins : 0,
      totalPoints : 0
    }
  }
  var r = {
    gameId : game._id,
    venueName : game.event.venue.name,
    rank : record.rank,
    score: record.score,
    cashedOutTime : record.cashedOutTime
  }

  var p1 = _.filter(stats.players, { '_id' : p._id });
  if (p1 && p1.length) {
    var x = p1[0];
    updateStats(x.stats, r);
    x.games.push(r);
  } else {
    updateStats(p.stats, r);
    p.games.push(r);
    stats.players.push(p);
  }

  function updateStats(stats, record) {
    stats.totalWins += (record.rank === 1) ? 1 : 0;
    stats.totalPoints += record.score;
    stats.bonusChips = Math.floor(stats.totalPoints / 10) * 100;
    stats.totalGames++;
  }

}

api.get('/players/:id', function(req, res){

  var unwind = {
    '$unwind': {
      'path': '$players'
    }
  }

  var match = {
    '$match': {
      'players.player' : mongoose.Types.ObjectId(req.params.id)
    }
  }

  var group = {
    '$group': {
      '_id': '$players.player',
      'games': {
        $push: {
          '_id': '$_id',
          'score': '$players.score',
          'rank': '$players.rank',
          'event': '$event',
          'gameNumber': '$number',
          'gameStartTime': '$startTime',
          'completed': '$completed',
          'inProgress': '$inProgress',
          'finalTable': '$finalTable',
          'cashedOutTime': '$players.cashedOutTime'
        }
      }
    }
  }

  Game
  .aggregate([unwind, match, group])
  .exec(function(err, games){
    if (err)
      console.error(err.stack);
    res.send(games);
  })
})

module.exports = api;<commit_msg>feature/RHP_50-create-seasonal-standings-api-and-view Consolidate method of getting player stats for one and all players to be the same<commit_after>var express = require('express'),
    api     = express.Router(),
    _       = require('lodash');
    mongoose = require('mongoose');

var Venues  = require('../models/venue'),
    Users   = require('../models/user'),
    Players = require('../models/player'),
    Event   = require('../models/event'),
    Game    = require('../models/game');

var unwind = {
  '$unwind': {
    'path': '$players'
  }
}

var group = {
  '$group': {
    '_id': '$players.player',
    'totalPoints': { '$sum': '$players.score'},
    'averageRank': { '$avg': '$players.rank'},
    'bestRank': {'$min': '$players.rank'},
    'worstRank': {'$max': '$players.rank'},
    'games': {
      $push: {
        '_id': '$_id',
        'score': '$players.score',
        'rank': '$players.rank',
        'event': '$event',
        'gameNumber': '$number',
        'gameStartTime': '$startTime',
        'completed': '$completed',
        'inProgress': '$inProgress',
        'finalTable': '$finalTable',
        'cashedOutTime': '$players.cashedOutTime'
      }
    }
  }
}

var sort = {
  '$sort': { 'startTime': -1 }
}

api.get('/players/:id', function(req, res){

  var match = {
    '$match': {
      'players.player' : mongoose.Types.ObjectId(req.params.id)
    }
  }

  var pipeline = [unwind, match, sort, group];

  Game
  .aggregate(pipeline)
  .exec(function(err, games){
    if (err)
      console.error(err.stack);
    res.send(games);
  })
})

api.get('/players', function(req, res){

  var pipeline = [unwind, sort, group];

  Game
  .aggregate(pipeline)
  .exec(function(err, games){
    if (err)
      console.error(err.stack);
    res.send(games);
  })
})


module.exports = api;
{'fraction_non_alphanumeric': 0.18290218270008085, 'fraction_numerical': 0.003839935327405012, 'mean_word_length': 2.0911930043722675, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4707943', 'n_tokens_mistral': 1712, 'n_tokens_neox': 1677, 'n_words': 324}