/*
 * Admin Routes
 */

var async = require('async');
var Exercise = require('../data/models/exercise');
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 loadExercise = require('./middleware/load_exercise');
var isAdmin = require('./middleware/is_admin');
var maxUsersPerPage = 15;
var maxExercisesPerPage = 15;

module.exports = function(app) {

app.get('/admin', loggedIn, isAdmin, function(req, res){
    res.render('admin/index', { title: 'Admin' });
  });

app.get('/admin/users', loggedIn, isAdmin, function(req, res, next){
    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('admin/users', {
          title: 'Users',
          users: users,
          page: page,
          lastPage: lastPage
        });
      });
    });
  });

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

////////////////////////////////////////////////

app.get('/admin/exercises', loggedIn, isAdmin, function(req, res, next){
    var page = req.query.page  && parseInt(req.query.page, 10) || 0;
    async.parallel([

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

        function(next) {
          Exercise.find({})
            //.sort('title', 1)
            .skip(page * maxExercisesPerPage)
            .limit(maxExercisesPerPage)
            .exec(next);
        }
      ],

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

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

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

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

        res.render('admin/exercises', {
          title: 'exercises',
          exercises: exercises,
          page: page,
          lastPage: lastPage
        });

      }
    );
  });

  app.get('/admin/exercises/new', loggedIn, isAdmin, function(req, res) {
    res.render('admin/newexercise', {title: "New Exercise"});
  });


  app.post('/admin/exercises/new', function(req, res, next) {
      console.log("/nreq.body" + JSON.stringify(req.body));
      var exercise = req.body;
         Exercise.create(exercise, function(err) {
        if (err) {
          if (err.code === 11000) {
            res.send('Conflict', 409);
          } else {
            if (err.name === 'ValidationError') {
              return res.send(Object.keys(err.errors).map(function(errField) {
                return err.errors[errField].message;
              }).join('. '), 406);
            } else {
              next(err);
            }
          }
          return;
        }
        res.redirect('/admin/exercises');
      });
    });

  app.get('/admin/exercises/:_id', loadExercise, function(req, res, next){
    res.render('admin/editexercise', {title: req.exercise.name,
      exercise: req.exercise
      });
  });

  app.post('/admin/exercises/:_id', function(req, res, next){
      console.log("Upsert data " + JSON.stringify(req.body));
      var exercise = req.body;
      console.log("Upsert exercise " + JSON.stringify(exercise));
      var docid = req.body._id;
      console.log("DOCID " + docid);
      delete exercise["_id"];
      console.log("Upsert document " + JSON.stringify(exercise));
      Exercise.findByIdAndUpdate(docid, exercise, {upsert: false}, function(err) {
        if (err) {
          if (err.code === 11000) {
            res.send('Conflict', 409);
          } else {
            if (err.name === 'ValidationError') {
              return res.send(Object.keys(err.errors).map(function(errField) {
                return err.errors[errField].message;
              }).join('. '), 406);
            } else {
              next(err);
            }
          }
          return;
        }
        res.redirect('/admin/exercises');
      });



  });


  app.del('/admin/exercises/:_id', loggedIn, isAdmin, loadExercise, function(req, res, next) {
    req.exercise.remove(function(err) {
      if (err) { return next(err); }
      res.redirect('/admin/exercises');
    });
  });

   app.post('/admin/exercises', function(req, res) {
          res.contentType('json');
          Exercise.findOne({name: req.body.name})
              .exec(function(err, exercise) {
                if (err) {
                  return next(err);
                }
                if (! exercise) {
                  return res.send(JSON.stringify({ "name": "true" }));
                }
               res.send(JSON.stringify({ "name": "false" }));
          });
    });


//////////////////////////////////////////


};