'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 cron_gather = require('./lib/cron_gather');
const cron_auto = require('./lib/cron_auto');
const control = require('./lib/controller');

const options = {
    useMongoClient: true
};

mongoose.connect(config.mongo, options);
console.log('MONGO CONNECT INFO: ', config.mongo);
global.Promise = mongoose.Promise = require('bluebird');
var expressWs = require('express-ws')(app);
app.ws('/echo', function(ws, req) {
	console.dir('inini');
  ws.on('message', function(msg) {
  	console.log(msg);
  	control.getDynamic(function(data){
  		try{
  			ws.send(data);
  		}catch(e){
  			console.dir(e);
  		}
  		
  	});
  });
  ws.on('close', function(msg) {
  	console.log(msg);
   //
  });
});
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){ req['session_body'] = flag.toJSON(); 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(process.env.NODE_ENV + 'server started on port ' + config.port);


if(process.env.NODE_ENV === 'production'){
	cron.start();
	cron_gather.start();
	cron_auto.start();
}

