var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var loginRouter = require('./routes/login');
var bookRouter = require('./routes/book');
var settingsRouter = require('./routes/settings');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.set('trust proxy', 1);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
    secret: require("./config.js").sessionHash,
    name: "sessionId",
    saveUninitialized: false,
    resave: true
}));
app.use(express.static(path.join(__dirname, 'public')));


// Prepare db
require("./src/sequelize.js").ready.then(() => {
    // Start file updater
    require("./src/files.js");

    app.use('/', indexRouter);
    app.use('/login', loginRouter);
    app.use('/book', bookRouter);
    app.use('/settings', settingsRouter);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      require('./src/templateArgs.js').generate(req).then(args => {
        res.status(err.status || 500);
        res.render('error', args);
      });
    });
});

module.exports = app;

