// base setup michael
var express = require('express');
var nodemailer = require('nodemailer');
var dateTimeService = require('./api/services/DateTimeService');
var mongoose = require('mongoose');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var config = require('./api/config/config');

var app = express();            // Main web app
var redirectApp = express();    // Redirection app if using secure connection (HTTPS)

// Set HOST
app.set("host", config.app.host);
app.set("protocol", config.app.protocol);
app.set("baseApiUrl", app.get("protocol") + "://" + app.get("host") + ":" + config.app.externalPort);
app.set("baseWebUrl", app.get("baseApiUrl") + "/#");

require('./deployment/gulpfile')(__dirname + '/webapp/');//this will take care to generate the distrib js and css files.
require('./api/services/ExistingProjectsNotificationService').configureNotifications('0 0 3 * * *', app);//setup existing projects notifications as daily

// Connect to mongodb
const { host, port, name } = config.db;  // Retrieve db config by unpacking
const databaseString = `mongodb://${host}:${port}/${name}`;
mongoose.connect(databaseString, {
    poolSize: 30,
    useMongoClient: true
});
mongoose.connection.on('error', function (err) {
    console.log(err);
});

var http = require('http');
var https = require('https');
if (config.app.secure) { // redirect http to https
    redirectServer = http.createServer(redirectApp);
    redirectApp.use(function requireHTTPS(req, res, next) {
        if (!req.secure) {
            return res.redirect('https://' + req.headers.host + req.url);
        }
        next();
    })

    redirectServer.listen(config.app.port);
}

require('./api/config/passport')(passport, app);
app.use(bodyParser.json({ limit: '5mb' }));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: true }));
app.use(cookieParser());

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
    next();
});

// Express Session configuration. Visit https://www.npmjs.com/package/express-session for more info.
app.set('trust proxy', config.app.secure); // Needs to be true if secure cookies is set to true
app.use(session({
    secret: 'ThisIsMyDirtyLittleSecretChocolatebunniesson',
    resave: true,               // Default option
    saveUninitialized: true,    // Default option
    cookie: {
        expires: dateTimeService.getDateOneYearFromNow(),
        secure: config.app.secure
    }
}));

app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

// set static files location
// used for requests that our frontend will make
app.use(express.static(__dirname + '/webapp', { maxage: '1d' }));
app.set('root', __dirname + '/webapp');

var userRoutes = require('./api/routes/userRoutes')(app, express);
var projectRoutes = require('./api/routes/projectsRoutes')(app, express);
var toDoRoutes = require('./api/routes/toDoRoutes')(app, express);
var profileRoutes = require('./api/routes/profileApi')(app, express);
var supportRoutes = require('./api/routes/support')(app, express);
var logRoutes = require('./api/routes/logRoutes')(app, express);
var settingsRoutes = require('./api/routes/settingsRoutes')(app, express);
var skillsRoutes = require('./api/routes/skillsRoutes')(app, express);

var courseFileRoutes = require('./api/routes/courseFileRoutes')(app, express);
var termRoutes = require('./api/routes/termRoutes')(app, express);
var courseRoutes = require('./api/routes/courseRoutes')(app, express);


app.use('/api', projectRoutes);
app.use('/vip', userRoutes);
app.use('/api', profileRoutes);
app.use('/todo', toDoRoutes);
app.use('/support', supportRoutes);
app.use('/log', logRoutes);
app.use('/settings', settingsRoutes);
app.use('/api', skillsRoutes);

app.use('/api', courseFileRoutes);
app.use('/api', termRoutes);
app.use('/api', courseRoutes);


// home page
app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname + '/webapp/index.html'));
});

if (config.app.secure) {
    var privateKey = fs.readFileSync(__dirname + '/privkey.pem');
    var certificate = fs.readFileSync(__dirname + '/cert.pem');
    var authority = fs.readFileSync(__dirname + '/chain.pem');

    const HTTPS_DEFAULT_PORT = 443;
    https.createServer({
        key: privateKey,
        cert: certificate,
        ca: authority
    }, app).listen(HTTPS_DEFAULT_PORT);
    //  http.createServer(app).listen(config.app.port);
} else {
    app.listen(config.app.port);
}

 console.log(`Web server now running at -> ${config.app.protocol}://${config.url} <-`);
