/**
 * Created by matthewpeters on 8/30/15.
 */
var Hapi = require('hapi')
var server = new Hapi.Server();
var Joi =require('joi');
var Boom = require('boom');
var db = require('./config/db');
var Config = require('./config/config');
var moment = require('moment');
var Inert = require('inert');

var app = {};
app.Config = Config;


server.connection({
    host: app.Config.server.host,
    port: app.Config.server.port,
    routes: {
        cors: true
    }
})

var privateKey = app.Config.key.privateKey;
var ttl = app.Config.key.tokenExpiry;


// Validate function to be injected
var validate = function(request, token, callback) {
    // Check token timestamp
    var diff = moment().diff(moment(token.iat * 1000));
    if (diff > ttl) {
        return callback(null, false);
    }
    callback(null, true, token);
};

// Plugins, register hapi-auth-jwt to server

server.register(Inert, function () {});
server.register([{
    register: require('hapi-auth-jwt')
}], function(err) {
    server.auth.strategy('token', 'jwt', {
        validateFunc: validate,
        key: privateKey
    });
});

server.route(require('./lib/routes'));

server.start(function () {
    console.log('Server running at:',server.info.uri);
});
