var express       = require('express')
var routes        = require('./routes');
var user          = require('./routes/user');
var http          = require('http');
var path          = require('path');

var partials      = require('express-partials');

var flash         = require('connect-flash')
var passport      = require('passport')
var util          = require('util')
var LocalStrategy = require('passport-local').Strategy;

var users_db      = require('./db/users');

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  users_db.findById(id, function (err, user) {
    done(err, user);
  });
});


passport.use(new LocalStrategy(
  function(username, password, done) {

    process.nextTick(function () {

      users_db.findUser(username, password, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Invalid Credentials' }); }
  
        return done(null, user);
      })
    });
  }
));

var app = express();

// configure Express
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat' }));
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(partials());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});


// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/'                         , routes.index);
app.get('/logout'                   , user.logout);
app.get('/home'                     , ensureAuthenticated, user.afterLoginPage);
app.get('/register'                 , user.register);
app.post('/addNewUser'              , user.addNewUser);
app.post('/updateAccount'           , ensureAuthenticated, user.updateAccount);
app.get('/dataLog'                  , ensureAuthenticated, user.dataLog);
app.get('/fromSystem/:data'          , user.addEntry);
app.get('/demo'                     , ensureAuthenticated, user.cc3000);
app.get('/demo2'                    , ensureAuthenticated, user.demo2);
app.post('/demo2Results'            , ensureAuthenticated, user.demo2Results);
app.post('/demoResults'             , ensureAuthenticated, user.testData);
app.get('/account'                  , ensureAuthenticated, user.account);


app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/', failureFlash: true }),
  function(req, res) {
    res.redirect('/home');
  });

app.listen(3000);


function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/')
}