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


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

  var check = ntr.checkToken(req, res) 


  if(check.name == false) {

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


    res.redirect(302, "/")
  }

  
});

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.name == null) {

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

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

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

       
    } else {    
        console.log("[Get] - GET[" + req.body.request + '-' + req.body.name + "]")
        if(req.body.request == "page") {
            
            try {
                const file = fs.readFileSync(__dirname.replace("routes", "public" + path.sep + "templates" + path.sep) + path.sep + req.body.name, 'utf-8') ;
                res.send({"result":"success", "content":file})
            } catch(error) {

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

        } else if(req.body.request == "accountpic") {
            try {
                const file = fs.readFileSync(__dirname.replace("routes", "images" + path.sep + "userspics" + path.sep) + path.sep + req.body.name  + ".png", 'utf-8') ;
                res.send({"result":"success", "content":file})
            } catch(error) {

                res.send({"result":"failed", "content":"ERROR_FILE_NOT_EXIST"})
            }
            
        } else if(req.body.request == "username") {

            res.send({"result":"success", "content": ntr.checkToken(req, res).name})
            
        
        } else if(req.body.request == "fullname") {

          res.send({"result":"success", "content": ntr.getFullName(ntr.checkToken(req, res).name)})
          
      
      } else if(req.body.request == "all") {

        if(check.permLevel == 4) {
          res.send({"result":"success", "content": ntr.getAll(req.body.name)})

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

        }

       
        
    
      } else {

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

        }
        
    }

   
    
  }


})

module.exports = router;
