var fs = require("fs")
var uuid = require('uuid')
var path = require("path")
var CryptoJS = require("crypto-js")
var Jimp = require("jimp")

module.exports.checkUser = () => {


    const userDir = fs.readdirSync(__dirname + path.sep + "users" + path.sep)


   if(userDir.length == 0) {
    
      this.createUser("root","neutral",4,"Administrateur")
   }

}


module.exports.createUser = (name, password, level, fullname) =>  {

    if(this.getUUID(name) == false) {
        

        const passcrypt = CryptoJS.AES.encrypt(password, "D*G-KaPdSgVkYp3s");
        const userUUID = uuid.v4();
        const userData = {
          "username":name,
          "password": passcrypt.toString(),
          "uuid": userUUID,
          "fullname": fullname,
          "permissionLevel":level,
          "token":{
    
    
          },
          "lastconnexion":0
    
        }

        const src = __dirname + path.sep + "public"  + path.sep + "images" + path.sep + "standalone.png"
        const dest = __dirname + path.sep + "public" + path.sep + "images" + path.sep + "userspics" + path.sep + name + ".png"

        fs.copyFileSync(src, dest)
        fs.writeFileSync(__dirname + path.sep + "users" + path.sep + userUUID + ".json", JSON.stringify(userData, null, 2)) 

        return "USER_CREATED"

    } else {
       
        return "USER_ALREADY_EXIST"
    }

   

    

}





module.exports.deleteUser = (name) =>  {

    const userUUID = this.getUUID(name)

    if(userUUID != false) {
        

        fs.rmSync(__dirname + path.sep + "users" + path.sep + userUUID + ".json")
        fs.rmSync(__dirname + path.sep + "public" + path.sep + "images" + path.sep + "userspics"+ path.sep + name+ ".png")

        return "USER_DELETED"

    } else {
       
        return "USER_ALREADY_DELETED"
    }


}

module.exports.deleteToken = (username) => {



    const userData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + this.getUUID(username) + ".json", 'utf-8'))
        
    userData.token = {}
        
    fs.writeFileSync(__dirname + path.sep + "users" + path.sep + this.getUUID(username) + ".json", JSON.stringify(userData, null, 2))

}

module.exports.checkToken = (req, res) => {

    const tokens = this.getAllToken()
    const users = this.getUsers()
    
    if(req.cookies.tokenID == null) {
        const checkTokenData = {"name":false}
        return checkTokenData;

    } else if(tokens.has(req.cookies.tokenID)) {
        const user = tokens.get(req.cookies.tokenID)
        const userData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + users.get(user) + ".json", 'utf-8'))

        userData.lastconnexion = Date.now()

        fs.writeFileSync(__dirname + path.sep + "users" + path.sep + userData.uuid + ".json", JSON.stringify(userData, null, 2))

        if(userData.token.livableToken == true) {

            const checkTokenData = {"name":user, "permLevel": userData.permissionLevel, "fullname":userData.fullname, "lastconnexion":userData.lastconnexion};
            return checkTokenData;
            
        } else {
            const tokenDate = new Date(userData.token.createdAt)
            const nowDate = new Date(Date.now())

            if(tokenDate.getDay() == nowDate.getDay() && tokenDate.getMonth() == nowDate.getMonth()) {

                const checkTokenData = {"name":user, "permLevel": userData.permissionLevel, "fullname":userData.fullname, "lastconnexion":userData.lastconnexion};
                return checkTokenData;
            } else {

                res.clearCookie('tokenID');
                const checkTokenData = {"name":false}
                return checkTokenData;
                
                
            }

        }

    } else {
        const checkTokenData = {"name":false}
        return checkTokenData;
    }

    

    
}

module.exports.getFullName = (username) => {
 
    const userData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + this.getUUID(username) + ".json", 'utf-8'))
    
    
    return userData.fullname

}

module.exports.generateTokenID = (username, userData, req, users) => {
    const tokenID = uuid.v4()
    const date = Date.now()
  
    var newUserData = userData;
    var livable = false;
  
    if(req.body.remindus == true) {
  
      livable = true;
    } 
  
    Object.defineProperties(newUserData, {
      token: {
        value: {
          "tokenID":tokenID,
          "livableToken": livable,
          "createdAt": date
        },
        writable: true
  
      }
  
    })
  
    fs.writeFileSync(__dirname + path.sep + "users" + path.sep + users.get(username) + ".json", JSON.stringify(newUserData, null, 2))
  
    return tokenID
  
}

module.exports.getUsers = () => {

    const users = new Map();

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

    })

    return users
}

module.exports.getAllToken = () => {

    const token = new Map();

    fs.readdirSync(__dirname + path.sep + "users").forEach(file => {
        const fileData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + file, 'utf-8'))
        token.set(fileData.token.tokenID, fileData.username)

    })

    return token
}

module.exports.getUUID = (username) => {

    const users = new Map();

    fs.readdirSync(__dirname + path.sep + "users").forEach(fileD => {
        
        const fileData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + fileD, 'utf-8'))
        users.set(fileData.username, fileData.uuid)

    })

    var data = users.get(username);

   

    if(typeof data == "undefined") {

        data = false
    }

    return data;
}


module.exports.changeFullName = (username, req, res) => {

    const userData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + this.getUUID(this.checkToken(req, res).name) + ".json", 'utf-8'))
   
    Object.defineProperties(userData, {
        fullname: {
          value: username,
          writable: true
    
        }
    
      })
    
    const user = this.getUUIDRequest(req);

    fs.writeFileSync(__dirname + path.sep + "users" + path.sep + user + ".json", JSON.stringify(userData, null, 2))

}

module.exports.getUUIDRequest = (req) => {

    const users = this.getUsers()
    const tokens = this.getAllToken()
    
    users.get(tokens.get(req.cookies.tokenID))

    if(req.cookies.tokenID == null) {
        
        return false;

    } else if(tokens.has(req.cookies.tokenID)) {
        
        return users.get(tokens.get(req.cookies.tokenID))

    } else {
        
        return false;
    }

   

}

module.exports.changePassword = (req, res) => {



    const userData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + this.getUUID(this.checkToken(req, res).name) + ".json", 'utf-8'))

    const oldp = CryptoJS.AES.encrypt(req.body.additional, "D*G-KaPdSgVkYp3s")
    const newp = CryptoJS.AES.encrypt(req.body.value, "D*G-KaPdSgVkYp3s")

    if(CryptoJS.AES.decrypt(oldp, "D*G-KaPdSgVkYp3s").toString(CryptoJS.enc.Utf8) == CryptoJS.AES.decrypt(userData.password, "D*G-KaPdSgVkYp3s").toString(CryptoJS.enc.Utf8)) {

        
        Object.defineProperties(userData, {
            password: {
            value: newp.toString(),
            writable: true
        
            }
        
        })
        
        const user = this.getUUIDRequest(req);

        fs.writeFileSync(__dirname + path.sep + "users" + path.sep + user + ".json", JSON.stringify(userData, null, 2))
        res.send({"result":"success", "content": "<span style='color:rgb(130, 255, 163);'>Le mot de passe a été changé avec succès.</span>"})
    } else {

        res.send({"result":"success", "content": "Le mot de passe actuel est éronné."})
    }

   

}

module.exports.getAll = (username) => {

    const users = this.getUsers()


    const userData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + users.get(username) + ".json", 'utf-8'))
    const allData = {"username":username, "permLevel": userData.permissionLevel, "fullname":userData.fullname, "lastconnexion":userData.lastconnexion};
    return allData

}


module.exports.editUser = (requestData) => {

    if(this.getUUID(requestData.original) != false) {

        const userData = JSON.parse(fs.readFileSync(__dirname + path.sep + "users" + path.sep + this.getUUID(requestData.original) + ".json", 'utf-8'))
        
        userData.token = {};
        userData.username = requestData.username;
        userData.fullname = requestData.fullname;
        userData.permissionLevel = requestData.permLevel;



        if(requestData.password != "") {

            userData.password = CryptoJS.AES.encrypt(requestData.password, "D*G-KaPdSgVkYp3s").toString()
        }


        fs.renameSync(__dirname + path.sep + "public" + path.sep + "images" + path.sep + "userspics" + path.sep + requestData.original + ".png",__dirname + path.sep + "public" + path.sep + "images" + path.sep + "userspics" + path.sep + requestData.username + ".png")
        fs.writeFileSync(__dirname + path.sep + "users" + path.sep + this.getUUID(requestData.original) + ".json", JSON.stringify(userData, null, 2)) 

        return true;

    } else {

        return false;
    }

}