//Express, Mongo & Environment specific imports
var express = require('express');
var morgan = require('morgan');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var compression = require('compression');
var errorHandler = require('errorhandler');

var mongo = require('./api/config/db');
var env = require('./api/config/env');

// Controllers/Routes import
var BookController = require('./api/controller/BookController');


//MongoDB setup
mongo.createConnection(env.mongoUrl);

//Express setup
var app = express();

//Express middleware
app.use(morgan('short'));
app.use(serveStatic(__dirname + '/app'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(compression());

var environment = process.env.NODE_ENV || 'development';
if ('development' == environment) {
	app.use(errorHandler({ dumpExceptions: true, showStack: true }));

	var ImportController = require('./api/controller/ImportController');
	app.get('/import', ImportController.import);
	app.get('/import/reset', ImportController.reset);
}



// Route definitions
app.get('/api/books', BookController.list);
app.get('/api/books/:id', BookController.show);
app.post('api/books', BookController.create);
app.put('/api/books/:id', BookController.update);
app.delete('/api/books/:id', BookController.remove);



var server = app.listen(3000, function () {
	var host = server.address().address;
	var port = server.address().port;
	console.log('Books app listening at http://%s:%s', host, port);
	console.log("Configured MongoDB URL: " + env.mongoUrl);
});




