var express = require('express');
var router = express.Router();

/* Login action */
router.post('/login', function(req, res) {
	var bcrypt = require('bcrypt-nodejs');
	
	var user = req.body.user,
		pass = req.body.pass;
	
	req.getConnection(function(err, connection) {
		if (err) throw err;
		
		var sql = " SELECT id, username, email, password, timezone, num_format " +
		" FROM todo_user " +
		" WHERE email = ? OR username = ? ";
		
		// Find the username / email
		connection.execute(sql, [user, user], function(err, rows, fields) {
			if (err) throw err;
			
			var user = rows[0];
			
			// Verify the password hash
			bcrypt.compare(pass, user.password, function(err, passRes) {
				if (err) throw err;
				
				// Password is good, set session data and redirect
				if (passRes === true)
				{
					req.session.uid = user.id;
					req.session.num_format = user.num_format;
					req.session.username = user.username;
					
					res.redirect(303, '/');
				}
			});
		});
	})
});

/* Logout action */
router.get('/logout', function(req, res) {
	// Destroy the session, and redirect to the index page
	req.session.destroy(function(err) {
		res.redirect(303, '/');
	});
});

/* GET users listing. */
router.get('/list', function(req, res) {
	res.send('respond with a resource');
});

router.get('/:id', function(req, res) {
	res.send('respond with a resource');
});

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

router.put('/:id', function(req, res) {
	res.send('respond with a resource');
});

router.delete('/:id', function(req, res) {
	res.send('respond with a resource');
});

module.exports = router;
