const fs = require('fs');
const path = require('path');
const { client, logch } = require("../index.js");
const logger = require("./logger.js");

const botconfig = JSON.parse(fs.readFileSync(path.resolve(`./config/botinfo.json`)));
let memberRoleID = botconfig.memberRoleID
const badwords = JSON.parse(fs.readFileSync(path.resolve(`./config/badwords.json`)));


function checkBadwords(msg) {
    badwordlist = badwords.filter(word => msg.content.toLowerCase().includes(word));
    return badwordlist;
}


module.exports = {
    // Check general properties of message
    general: function (message) {
        fs.stat(`./data/users/${message.author.id}.json`, function (err, stat) {
            if (err == null) {
                // Check if the message is safe for community
                suspiciousWords = checkBadwords(message);
                if (suspiciousWords.length > 0) {
                    logger.all(`${message.author.tag} a dit ${suspiciousWords.toString()} dans ${message.channel.name}`);
                }


            } else if (err.code === 'ENOENT') {
                // If it is the first message of the member we give him member role except if his messages contains suspicious words
                suspiciousWords = checkBadwords(message);
                if (suspiciousWords.length > 0) {
                    return logger.all(`${message.author.tag} a dit ${suspiciousWords.toString()} dans ${message.channel.name}`);
                }
                actualtimestamp = + new Date();
                usrinfo = {
                    id: message.author.id,
                    hasleft: false,
                    join: actualtimestamp,
                    left: 0
                }
                const jsonStringusr = JSON.stringify(usrinfo);
                fs.writeFile(`./data/users/${message.author.id}.json`, jsonStringusr, err => {
                    if (err) {
                        console.log(`Error writing user profile`, err)
                    } else {
                        console.log(`Successfully wrote user profile`)
                    }
                });

                memberRole = message.guild.roles.cache.find(role => role.id == memberRoleID);
                message.member.roles.add(memberRole);


            } else {
                console.log('Error: ', err.code);
            }
        });
    },


    // Update profile
    memberUpdate: function (member, event) {
        fs.stat(`./data/users/${member.user.id}.json`, function (err, stat) {
            actualtimestamp = + new Date();
            if (err == null) {
                oldusrinfo = JSON.parse(fs.readFileSync(path.resolve(`./data/users/${member.user.id}.json`)));
                if (event == "join") {
                    joininfo = actualtimestamp;
                    leftinfo = oldusrinfo.left;
                    hasleftinfo = false;
                    memberRole = member.guild.roles.cache.find(role => role.id == memberRoleID);
                    member.roles.add(memberRole);

                } else if (event == "left") {
                    leftinfo = actualtimestamp;
                    joininfo = oldusrinfo.join;
                    hasleftinfo = true;
                }
                usrinfo = {
                    id: member.user.id,
                    hasleft: hasleftinfo,
                    join: joininfo,
                    left: leftinfo,
                }
                const jsonStringusr = JSON.stringify(usrinfo);
                fs.writeFile(`./data/users/${member.user.id}.json`, jsonStringusr, err => {
                    if (err) {
                        console.log(`Error writing user profile`, err)
                    } else {
                        console.log(`Successfully wrote user profile`)
                    }
                });


            } else if (err.code === 'ENOENT') {

                if (event == "join") {
                    logger.all("Il doit donc se présenter dans le channel 👋-présentation");
                } else if (event == "left") {
                    leftinfo = actualtimestamp;
                    joininfo = 0;
                    hasleftinfo = true;
                  	logger.all("Mais il n'avait jamais parlé sur le serveur");
                }
            } else {
                console.log('Error: ', err.code);
            }
        });
    }
}