var express = require('express');
var router = express.Router();
var path = require("path")
var fs = require("fs")
var CryptoJS = require("crypto-js");
var uuid = require("uuid")
var ntr = require("../neutral-functions.js")

/* GET home page. */
router.get('/', function(req, res, next) {

  
  ntr.checkUser()
  var check = ntr.checkToken(req, res) 

  if(check.name != false) {

    res.redirect(302, "/")
   
  } else {

    res.render('login', {error: ""});
  }

});


router.post("/", function(req, res, next) {


  const users = new Map();

  fs.readdirSync(__dirname.replace("routes", "users")).forEach(file => {
    const fileData = JSON.parse(fs.readFileSync(__dirname.replace("routes", "users") + path.sep + file))
    users.set(fileData.username, fileData.uuid)

  })

  const bod = req.body

  if(users.has(bod.username)) {

    const userData = JSON.parse(fs.readFileSync(__dirname.replace("routes", "users") + path.sep + users.get(req.body.username) + ".json"))
    var userpassword = CryptoJS.AES.decrypt(userData.password,"D*G-KaPdSgVkYp3s").toString(CryptoJS.enc.Utf8)

    if(bod.password == userpassword) {
      
      userpassword = null;

      const tokenID = ntr.generateTokenID(bod.username, userData, req, users)

      res.cookie('tokenID' , tokenID, { maxAge: 900000000, httpOnly: true })
      res.status(202).send({"token":"auth_success"})

    } else {
      userpassword = null;
      res.status(202).send({"token":"auth_failed"})
    
    }


    

  } else {
    res.status(202).send({"token":"auth_failed"})
    
  }
  
 

})



module.exports = router;
