const express = require('express'),
    router = express.Router(),
    templateArgs = require('../src/templateArgs.js'),
    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.findOne({
    where: {
      username: req.body.username,
      password: require('sha256')(req.body.password)
    }
  }).then(val => {
    if (val) {
      req.session.userId = val.id;
      res.redirect("/");
    } else {
      renderLogin(req, res, true);
    }
  });
});

module.exports = router;
