'use strict';

const express = require('express');
const path = require('path');
const config = require('./config/index');
const logger = require('morgan');

const app = express();
const routes = require('./routes/index');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('cookie-session');
const mongoose = require('mongoose');
const sessions = require('./db/mongo/session');
const cron = require('./lib/cron');

const options = {
    useMongoClient: true
};

mongoose.connect(config.mongo, options);
console.log('MONGO CONNECT INFO: ', config.MONGO_DB);
global.Promise = mongoose.Promise = require('bluebird');

app.use(logger('dev'));
app.use(cookieParser('f7f926ad3fc8fe90eb4784643bc4d747'));
app.use(session({secret: '5f1d65f27e370c36dfd845f6dc78b869'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(__dirname+'/app'));
app.use(async function(req,res,next){
	if(req.url == '/session' || req.url == '/') return next();
	let sess = req.cookies['sess'];
	let flag = await sessions.findById(sess)
	if(flag) return next();
	else res.redirect('/');
});
app.get('/', function (req, res){
	console.dir('login');
  	res.sendFile(path.resolve(__dirname, 'app', 'index.html'))
});
app.get('/manage', function (req, res){
  	res.sendFile(path.resolve(__dirname, 'app', 'index.html'))
});
app.get('/manage/*', function (req, res){
  	res.sendFile(path.resolve(__dirname, 'app', 'index.html'))
});
app.use(routes);


app.listen(config.port);
console.log('server started on port ' + config.port);

cron.start();
