'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Team = mongoose.model('Team'),
	_ = require('lodash');

/**
 * Create a Team
 */
exports.create = function(req, res) {
	var team = new Team(req.body);
	team.user = req.user;

	team.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(team);
		}
	});
};

/**
 * Show the current Team
 */
exports.read = function(req, res) {
	res.jsonp(req.team);
};

/**
 * Update a Team
 */
exports.update = function(req, res) {
	var team = req.team ;

	team = _.extend(team , req.body);

	team.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(team);
		}
	});
};

/**
 * Delete an Team
 */
exports.delete = function(req, res) {
	var team = req.team ;

	team.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(team);
		}
	});
};

/**
 * List of Teams
 */
exports.list = function(req, res) { Team.find().sort('-created').populate('user', 'displayName').exec(function(err, teams) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(teams);
		}
	});
};

/**
 * Team middleware
 */
exports.teamByID = function(req, res, next, id) { Team.findById(id).populate('user', 'displayName').exec(function(err, team) {
		if (err) return next(err);
		if (! team) return next(new Error('Failed to load Team ' + id));
		req.team = team ;
		next();
	});
};

/**
 * Team authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.team.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
@@ -167,16 +167,181 @@
 lodash')
+,%0A%09populateTeamQuery = %5B%0A%09%7B%0A%09%09path:'user',%0A%09%09select:'_id displayName'%0A%09%7D,%0A%09%7B%0A%09%09path:'league',%0A%09%09select:'_id name'%0A%09%7D,%0A%09%7B%0A%09%09path: 'players',%0A%09%09select: '_id name'%0A%09%7D%0A%5D
 ;%0A%0A/**%0A 
@@ -1335,17 +1335,18 @@
 , res) %7B
- 
+%0A%09
 Team.fin
@@ -1375,37 +1375,33 @@
 opulate(
-'user', 'displayName'
+populateTeamQuery
 ).exec(f
@@ -1643,17 +1643,18 @@
 t, id) %7B
- 
+%0A%09
 Team.fin
@@ -1676,29 +1676,25 @@
 ate(
-'user', 'displayName'
+populateTeamQuery
 ).ex
@@ -2056,12 +2056,13 @@
 %0A%09next();%0A%7D;
+%0A

Add Team population query