var express = require('express');
const { compileString } = require('sass');
var router = express.Router();
var fs = require("fs")
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, "/login")
    
  } else {

    res.render('index', { title: ntr.getFullName(check.name), username: ntr.getFullName(check.name), accountpic: '<img width="200" class="w-25 sidebar-image noside" src="images/userspics/' + check.name + '.png">' });
  
  }

  
});

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

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

                const linkn = req.body.value

                const linkData = JSON.parse(fs.readFileSync(__dirname.replace("routes",'links.json')))

                if(linkn.src.includes(" ") | linkn.dest.includes(" ")) {

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

                } else if(Object.keys(linkData).includes(linkn.name)) {

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


                } else if(checkDest(linkn.dest) == true) {
                    
                    res.send({"result":"success", "content":"DEST_ALREADY_USED"})


                } else {

                    linkData[linkn.name] = {
                        "src": linkn.src.toLowerCase(),
                        "dest": linkn.dest.toLowerCase()

                    }

                    fs.writeFileSync(__dirname.replace("routes",'links.json'), JSON.stringify(linkData, null, 2))

                    loadLinksSaved()

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

                }
            } else if(req.body.request == "del") {

                const linkData = JSON.parse(fs.readFileSync(__dirname.replace("routes",'links.json')))

                Reflect.deleteProperty(linkData,req.body.value)

                fs.writeFileSync(__dirname.replace("routes",'links.json'), JSON.stringify(linkData, null, 2))


                
                loadLinksSaved()

            } else if(req.body.request == "get") {


                const linkData = JSON.parse(fs.readFileSync(__dirname.replace("routes",'links.json')))

                const links = Object.keys(linkData)

                var allLink = new Array()

                for(var link of links) {

                    allLink.push({"name": link, "src":linkData[link].src, "dest":linkData[link].dest})

                }

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



            } else if(req.body.request == "edit") {

    

                const linkn = req.body.value

                const linkData = JSON.parse(fs.readFileSync(__dirname.replace("routes",'links.json')))

                if(linkn.src.includes(" ") | linkn.dest.includes(" ")) {

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

                }  else if(checkName(linkn.name, linkData) == true) {

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


                }else if(checkDest(linkn.dest, linkn.original) == true) {
                    
                    res.send({"result":"success", "content":"DEST_ALREADY_USED"})


                } else {

                    Reflect.deleteProperty(linkData, req.body.value.original)

                    linkData[linkn.name] = {
                        "src": linkn.src.toLowerCase(),
                        "dest": linkn.dest.toLowerCase()

                    }

                    fs.writeFileSync(__dirname.replace("routes",'links.json'), JSON.stringify(linkData, null, 2))

                    loadLinksSaved()

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

                }

            }

        } else {

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

})

loadLinksSaved()

function loadLinksSaved() {

    const linkData = JSON.parse(fs.readFileSync(__dirname.replace("routes",'links.json')))
    const links = Object.keys(linkData)

  
    for(var link of links) {

        const dest = linkData[link].dest
        const src = linkData[link].src

        router.get('/' + dest, function (req, res, next) {

            res.redirect(302, src)

        })
        
    }
    

}

function checkDest(src, name) {


    if(name == null) {

        const linkData = JSON.parse(fs.readFileSync(__dirname.replace("routes",'links.json')))
        const links = Object.keys(linkData)
        const destNotAvb = new Array()
    
        for(var link of links) {
    
            destNotAvb.push(linkData[link].dest)
        }
    
        if(destNotAvb.includes(src)) {
    
            return true;
        } else {
    
            return false;
    
        }
    
    } else {

        const linkData = JSON.parse(fs.readFileSync(__dirname.replace("routes",'links.json')))
        const links = Object.keys(linkData)
        const destNotAvb = new Array()
    
        for(var link of links) {

            if(link != name) {

                destNotAvb.push(linkData[link].dest)
            }
    
            
        }

       
    
        if(destNotAvb.includes(src)) {
    
            return true;
        } else {
    
            return false;
    
        }
    
    }

  
   
}

function checkName(name, linkData) {

    const names = Object.keys(linkData)
    const namewithout = new Array()

    for(var namei of names) {

        if(namei != name) {

            namewithout.push(linkData[namei].name)
        }

        
    }

    
    if(namewithout.includes(name)) {
    
        return true;
    } else {

        return false;

    }


  
   
}



module.exports = router;
