const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const express = require('express');
const handlebars = require('express-handlebars');
const stylus = require('stylus');
const config = require('./config');

const middleware = {
    devAuth: require('./middleware/dev_auth'),
    check: require('./middleware/check'),
    session: require('./middleware/session')
};

let app = express();
let hbs = handlebars.create({
    extname: '.hbs',
    defaultLayout: 'index',
    helpers: require('./util/hbs_helpers')
});

app.engine('.hbs', hbs.engine);
app.set('view engine', '.hbs');

require('./util/common/patch');

app.use(stylus.middleware({
    src: './styles/',
    dest: './compiled/css/'
}));

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(__dirname + '/compiled'));

app.use(middleware.check.skipped);
app.use(require('./middleware/setup'));

if (config.env === 'development') {
    app.use(middleware.devAuth.pickAuthData);
}
else {
    app.use(require('./middleware/tvm_init'));
    app.use(require('./middleware/blackbox'));
}

app.use(middleware.session);

if (/^(development|.*\.test)$/.test(config.env))
    app.get('/auth_data', middleware.devAuth.proxyAuthData);

// для сабмита форм с авторедиректом
app.use('/forms', require('./middleware/api'));
// для получения данных
app.use('/fetch', require('./middleware/fetch'));

const ROUTE_MAP = require('./config/routes.json');

Object.keys(ROUTE_MAP).forEach(key => {
    app.get(ROUTE_MAP[key], require(`./middleware/${key}`));
});

if (require.main === module) {
    app.listen(config.server.port, () => {
        console.log('app started');
    });
}
else {
    module.exports = app;
}
