var express = require('express');
var router = express.Router();
var templateArgs = require('../src/templateArgs.js');
var User = require("../src/sequelize.js").User();

function renderLogin(req, res, loginFailure) {
  templateArgs.generate(req).then(args => {
    args.title = "Totoro Book - Login";
    args.failure = !!loginFailure;
    res.render('login', args);
  });
}

router.get('/', (req, res, next) => {
  if (req.session.userId)
    res.redirect("/");
  else
    renderLogin(req, res);
});

router.post('/', (req, res) => {
  User.findAll({
    where: {
      username: req.body.username,
      password: require('sha256')(req.body.password)
    }
  }).then(val => {
    if (val && val[0]) {
      req.session.userId = val[0].id;
      res.redirect("/");
    } else {
      renderLogin(req, res, true);
    }
  });
});

module.exports = router;
