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) {

  
  var check = ntr.checkToken(req, res) 

  if(check.name != false) {

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

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

});

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

  var check = ntr.checkToken(req, res) 
  
  if(check.name == false) {

    res.send({"result":"failed", "content":"ERROR_TOKEN_NOT_VALID"})
    
    
  } else {

    if(req.body.request == null | req.body.value == null | req.body.additional == null) {

      if(req.body.request == null) {

        res.send({"result":"failed", "content":"ERROR_REQUEST_MISSING_FIELDS", "additional": "REQUEST_MISSING"})
      } else if(req.body.value == null){

        res.send({"result":"failed", "content":"ERROR_REQUEST_MISSING_FIELDS", "additional": "VALUE_MISSING"})
      } else {

        res.send({"result":"failed", "content":"ERROR_REQUEST_MISSING_FIELDS", "additional": "ADDITIONAL_MISSING"})

      }
        

       
    } else {    
        console.log("[Set] - SET[" + req.body.request + '-' + req.body.value + "-" + req.body.additional+ "]")

        if(req.body.request == "password") {

          ntr.changePassword(req, res);
          
          
            
        
        } else if(req.body.request == "fullname") {

        
            
            ntr.changeFullName(req.body.value, req, res);
            res.send({"result":"success", "content": "<span style='color:rgb(130, 255, 163);'>Le nom complet a été changé avec succès.</span>", "additional": req.body.value})
          
      
        }  else {

            res.send({"result":"failed", "content":"ERROR_REQUEST_NOT_VALID"})

        }
        
    }

   
    
  }


})

module.exports = router;


