'use strict';

const Express = require('express');
const Mongoose = require('mongoose');
const MethodOverride = require('method-override');
const BodyParser = require('body-parser');
const _ = require('lodash');
const crawlerRouter = require('./lib');

const app = Express();
const port = process.env.PORT || 3000;

app.use(Express.static(__dirname+'/client'));

// Add middleware nessary for Rest Api's
app.use(BodyParser.urlencoded({extended:true}));
app.use(BodyParser.json());
app.use(MethodOverride('x-HTTP-method-Override'));

// CORS Support
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.use('/crawler/', crawlerRouter);

// Connect to MongoDB
// Mongoose.connect('mongodb://localhost/appcrawler');
Mongoose.connect('mongodb://root:trust4appdbuser@ds038547.mlab.com:38547/trust4app');
Mongoose.connection.once('open', function () {

  // Load the models.
  app.models = require('./models');

  // Load the routes.
  var dbRoutes = require('./controllers');
  _.each(dbRoutes, function (controller, route) {
    app.use(route, controller(app, route));
  });

  app.listen(port, function () {
    console.log('Server started on port', port);
  });
});
