/*
 * User Routes
 */
var async = require('async');
var User = require('../data/models/user');
var notLoggedIn = require('./middleware/not_logged_in');
var loggedIn = require('./middleware/logged_in');
var loadUser = require('./middleware/load_user');
var isAdmin = require('./middleware/is_admin');
var restrictUserToSelf = require('./middleware/restrict_user_to_self');
var maxUsersPerPage = 5;
var maxWorkoutsPerPage = 5;
var Workout = require('../data/models/workout');

module.exports = function(app) {


  app.get('/users', loggedIn, isAdmin, function(req, res, next){
    res.redirect('/users/' + req.session.user.username);
    // var page = req.query.page && parseInt(req.query.page, 10) || 0;

    // User.count(function(err, count) {
    //   if (err) {
    //   return next(err);
    //   }
    //   var lastPage = (page + 1) * maxUsersPerPage >= count;

    //   User.find({})
    //   .sort('name')
    //   .skip(page * maxUsersPerPage)
    //   .limit(maxUsersPerPage)
    //   .exec(function(err, users) {
    //     if (err) {
    //        return next(err);
    //     }
    //     res.render('users/index', {
    //       title: 'Users',
    //       users: users,
    //       page: page,
    //       lastPage: lastPage
    //     });
    //   });
    // });
  });

  app.get('/users/new', notLoggedIn,   function(req, res) {
    res.render('users/new', {title: "New User"});
  });

  app.get('/users/:name', loadUser, function(req, res, next){
    // req.user.recentworkouts(function(err, workouts) {
    // if (err) {
    // return next(err);
    // }

    var page = req.query.page  && parseInt(req.query.page, 10) || 0;
    async.parallel([

        function(next) {
          Workout.count(next);
        },

        function(next) {
          Workout.find({})
            //.sort('title', 1)
            .populate('elements.exerciseID')
            .skip(page * maxWorkoutsPerPage)
            .limit(maxWorkoutsPerPage)
            .exec(next);
            console.log("exercise search finsihed");
        }
      ],

      //  callback from async
      function(err, results) {

        if (err) {
          return next(err);
        }

        var count = results[0];
        var workouts = results[1];

        var lastPage = (page + 1) * maxWorkoutsPerPage >= count;



    res.render('users/profile', {
    title: 'User profile',
    user: req.user,
    requested: req.params.name,
    recentworkouts: workouts
    });
    });
  });

  app.get('/users/:name/sidebar', loadUser, function(req, res, next){
    res.render('users/sidebar', {
      user: req.user,
      requested: req.params.name
      });
  });



  app.post('/users', notLoggedIn, function(req, res, next) {
    User.create(req.body, function(err) {
        if (err) {
           if (err.code === 11000) {
              res.send('Conflict', 409);
        } else {
          next(err);
        }
        return;
      }
      res.redirect('/users');
    });
  });

  app.del('/users/:name', loadUser,
    function(req, res, next) {
      req.user.remove(function(err) {
        if (err) { return next(err); }
        res.redirect('/users');
      });

  });

};