
/*!
 * Module dependencies.
 */

// Note: We can require users, articles and other cotrollers because we have
// set the NODE_PATH to be ./app/controllers (package.json # scripts # start)

var users = rekuire('users');
var sectionTypes = rekuire('sectionTypes')
var documents = rekuire('documents')
var sections = rekuire('sections')
var mv =require('mv')
var async=require('async')
var elderwand = require('elderwand')
var auth = require('./middlewares/authorization');
var BaseController = require('elderwand').BaseController;
var autoLayouts = BaseController.getChildControllers();

/**
 * Route middlewares
 */

var noauth = [];
var requiresLogin = [auth.requiresLogin];

/**
 * Expose routes
 */
var whitelist = [
      '/users/authtoken',
      '/users/forgotPassword',
      '/logout',
      '/authtail',
  ]
module.exports = function (app, passport) {
  // user routes
  app.use(function(req,res,cb){
  if (req.files) {
      async.each(Object.keys(req.files), function(key, next){
        if(req.files[key].isArray()){
          async.each(req.files[key], function(file, tick){
            file["newPath"] = "./tempUploads/" + file.name
            mv(file.path, file.newPath, tick)
          }, next)
        }else{
          req.files[key]["newPath"] = "./tempUploads/" + req.files[key].name
          mv(req.files[key].path, req.files[key].newPath, next)
        } 
      }, cb)
    }
  });
app.use(function(req, res, cb){
    req.anyKey = {}
    req.anyKey.inject(req.query)
    req.anyKey.inject(req.body)
    req.anyKey.inject(req.params)
    cb();
  });


  app.get('/login', users.login);
  app.get('/signup', users.signup);
  app.get('/logout', users.logout);
  app.post('/users', users.create);
  app.post('/users/session',
    passport.authenticate('local', {
      failureRedirect: '/login',
      failureFlash: 'Invalid email or password.'
    }), users.session);
  app.get('/users/:userId', users.show); 
  app.param('userId', users.load);

    


    


  /**    
   * Error handling
   */
  elderwand.toolBox.Routes.setupRoutes(app, requiresLogin, noauth, requiresLogin, noauth);
  app.get('/', noauth,documents.index);
  app.use(function (err, req, res, next) {
    // treat as 404
    if (err.message
      && (~err.message.indexOf('not found')
      || (~err.message.indexOf('Cast to ObjectId failed')))) {
      return next();
    }
    console.error(err.stack);
    // error page
    res.status(500).render('500', { error: err.stack });
  });

  // assume 404 since no middleware responded
  app.use(function (req, res, next) {
    res.status(404).render('404', {
      url: req.originalUrl,
      error: 'Not found'
    });
  });
}
