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

/* 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(check.permLevel >= 3) {

            const bod = req.body

            if(bod.request == "add") {
              
                res.send({"result":"failed", "content":"ERROR_NOT_MAKE"})

            } else if(bod.request == "get") {

                var files = new Array()
                const directory = req.body.value
                fs.readdir(directory.replace("/", path.sep.replace("\\", path.sep)), (err, data) => {

                    if(err) {
                        res.send({"result":"success", "content": "ERROR_NOT_EXIST"})
                        
                    } else {    

                        try {
                       
                            for(var file of data) {

                           
                                const stat = fs.statSync(directory.replace("/", path.sep.replace("\\", path.sep)) + path.sep + file)
                              
                                files.push({"name":file, "type":mime.lookup(file), "size":stat.size, "lastedition":stat.mtimeMs, "directory":stat.isDirectory()})


                            } 

                            res.send({"result":"success", "content": files})


                        } catch(err) {

                                res.send({"result":"success", "content": "ERROR_NOT_PERMITTED"})

                        }

                        
                    }

                })
                
                
                
            
            } else if(bod.request == "del") {
                
                res.send({"result":"failed", "content":"ERROR_NOT_MAKE"})

            } else if(bod.request == "rename") {

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

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

    }

})

module.exports = router;
