let express = require('express');
let router = express.Router();
let passwd = 'insecure';

let low = require('lowdb'),
config = low('config.json');

let tbdLabel = config.get('mainConfig').chain().find({ param: 'tbdLabel' }).value()['value'];
let byeLabel = config.get('mainConfig').chain().find({ param: 'byeLabel' }).value()['value'];


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { mainHeader: '🍺🍺🍺 Aktueller Spielstand 🍺🍺🍺🍺', TBD:tbdLabel, NoTeam:byeLabel });
});

router.get('/login', function(req, res, next) {
  console.log(req.session.passwd);
  console.log(req.session);
  if(req.session.passwd=='insecure'){
    res.redirect('/admin');
  }else{
    res.render('login', { mainHeader: 'Please Login' }); 
  }
});

router.post('/login', function(req, res, next) {
  if(req.body.passwd=='insecure'){
    req.session.passwd='insecure';
    console.log('set');
    res.end('done')
  }else{
    res.end('invalid')
  }
});

router.get('/admin', function(req, res, next) {
  console.log(req.session.passwd);
  console.log(req.session);
  if(req.session.passwd=='insecure'){
    res.render('admin', { mainHeader: 'Admin Interface', TBD:tbdLabel, NoTeam:byeLabel });
  }else{
    res.redirect('/login');
  }
});

module.exports = router;
//Nice trick to get io into my routes, not really needed right now
// http://stackoverflow.com/questions/24609991/using-socket-io-in-express-4-and-express-generators-bin-www
/*
module.exports = (io) => {
    var app = require('express');
    var router = app.Router();

    io.on('connection', function(socket) {
    });
    return router;
};
*/
