// Base setup
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Sequelize = require('sequelize');
// var cookieParser = require('cookie-parser');
var session      = require('express-session');

var passport   = require('passport');
var flash    = require('connect-flash');
var jwt         = require('jwt-simple');

var router = express.Router();

//DB setup
var env       = process.env.NODE_ENV || "development";
var config    = require(__dirname +'/config/config.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);

// Configure express to use body-parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// app.use(cookieParser('keyboard cat'));

// For Passport
app.use(session({ secret: 'keyboard cat',cookie: { httpOnly: false, maxAge: 900000},rolling: true, resave: true, saveUninitialized:true})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

app.use(flash());
//Models
var models = require("./models");




// Setting server port
var port = 3000;

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin',  'http://localhost');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

//Check database connection
sequelize.authenticate().then(function(err) {
  if(err)
    console.log('Unable to connect to database: ', err);
  console.log('Connected to database.');
});

// routes
app.use(require('./routes'));

// Starting server
app.listen(port);
console.info('Let the magic happen.');
require('./config/passport/passport.js')(passport,models.user);
