const dc = require("discord.js");
const client = new dc.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const fs = require("fs");

function isDir(path){
    try{
        fs.readdirSync(path);
        return true;
    } catch(e){
        return false;
    }
}

function parseCommands(){
    var cmdFiles = [];
    var indexes = {}
    var rootdir = fs.readdirSync("Juustobotti/commands");
    rootdir.forEach(categorydir => {
        if(!isDir("Juustobotti/commands/" + categorydir)) return;
        if(categorydir == "fun") return;
        fs.readdirSync("Juustobotti/commands/" + categorydir).forEach(file => {
            if(isDir("Juustobotti/commands/" + categorydir + "/" + file)) return;
            if(file == "rockpaperscissors.js") return;
            cmdFiles.push({file: file, dir: categorydir});
        });
    });
    var cmds = [];
    cmdFiles.forEach(yes => {
        var cmdObj = require("./Juustobotti/commands/" + yes.dir + "/" + yes.file);
        cmds.push(cmdObj);
    });
    return cmds;
}

var shapes = ["rock", "paper", "scissors"];
function rps(shape){
    shape = shape.toLowerCase();
    var chosenShape = shapes[Math.floor(Math.random()*shapes.length)];
    var beats = {
        paper: "scissors",
        scissors: "rock",
        rock: "paper"
    }
    if(beats[chosenShape] == shape) return "Win";
    if(beats[shape] == chosenShape) return "Loose";
    return "Tie";
}

client.on("ready", () => {
    console.log("Ready!");
    client.guilds.cache.get("733451782063390790").commands.set([
        {
            name: "ping",
            description: "Shows my latency xDDDDDDDD"
        },
        {
            name: "rps",
            description: "Rock paper scissors in a nutshell.",
            options: [
                {
                    name: "firstmove",
                    description: "First move, yk to start it all off",
                    type: 3,
                    required: true
                }
            ]
        }
    ]);
});

client.on("interactionCreate", (int) => {
    if(int.isCommand()){
        if(int.commandName == "ping"){
            int.reply(`Pong! (${client.ws.ping} ms)`);
        } else if(int.commandName == "rps"){
            var shape = int.options.getString("firstmove").toLowerCase().replace(/​/g, "");
            if(!shapes.includes(shape)) return int.reply("That isn't a valid shape.");
            var msgRow = new dc.MessageActionRow();
            var rockButton = new dc.MessageButton();
            rockButton.setCustomId("rock");
            rockButton.setLabel("Rock");
            rockButton.setEmoji(int.guild.emojis.cache.get("<:rock:915328258126528582>"));
            rockButton.setStyle("PRIMARY");
            var paperButton = new dc.MessageButton();
            paperButton.setCustomId("paper");
            paperButton.setLabel("Paper");
            paperButton.setEmoji(int.guild.emojis.cache.get("<:paper:915328929294864494>"));
            paperButton.setStyle("PRIMARY");
            var scissorsButton = new dc.MessageButton();
            scissorsButton.setCustomId("scissors");
            scissorsButton.setLabel("Scissors");
            scissorsButton.setEmoji(int.guild.emojis.cache.get("<:scissors:915329041958043648>"));
            scissorsButton.setStyle("PRIMARY");
            msgRow.addComponents(rockButton);
            msgRow.addComponents(paperButton);
            msgRow.addComponents(scissorsButton);
            var embed = new dc.MessageEmbed();
            embed.setFooter("rps");
            embed.addField("Moves", shape);
            var status = rps(shape);
            if(status == "Win"){
                embed.setColor("#00FF00");
                embed.setTitle("Win");
                embed.setDescription("You insta-won the game!");
            } else if(status == "Loose"){
                embed.setColor("#FF0000");
                embed.setTitle("Lose");
                embed.setDescription("You insta-lost the game, better luck next time!");
            } else if(status == "Tie"){
                embed.setColor("LIGHT_GREY");
                embed.setTitle("Tie");
                embed.setDescription("And the games continue, this game is currently on tie, press a button to continue.");
            }
            int.reply({embeds: [embed], components: [msgRow]});
        }
    } else if(int.isButton()){
        console.log("Button detected");
        if(!int.message.embeds[0]) return console.log("Nu embed");
        var msgEmbed = int.message.embeds[0];
        if(msgEmbed.footer.text == "rps"){
            var shape = int.customId;
            if(msgEmbed.title !== "Tie") return int.reply("This game has already ended!");
            var msgRow = new dc.MessageActionRow();
            var rockButton = new dc.MessageButton();
            rockButton.setCustomId("rock");
            rockButton.setLabel("Rock");
            rockButton.setEmoji(int.guild.emojis.cache.get("<:rock:915328258126528582>"));
            rockButton.setStyle("PRIMARY");
            var paperButton = new dc.MessageButton();
            paperButton.setCustomId("paper");
            paperButton.setLabel("Paper");
            paperButton.setEmoji(int.guild.emojis.cache.get("<:paper:915328929294864494>"));
            paperButton.setStyle("PRIMARY");
            var scissorsButton = new dc.MessageButton();
            scissorsButton.setCustomId("scissors");
            scissorsButton.setLabel("Scissors");
            scissorsButton.setEmoji(int.guild.emojis.cache.get("<:scissors:915329041958043648>"));
            scissorsButton.setStyle("PRIMARY");
            msgRow.addComponents(rockButton);
            msgRow.addComponents(paperButton);
            msgRow.addComponents(scissorsButton);
            var embed = new dc.MessageEmbed();
            embed.setFooter("rps");
            var moves = msgEmbed.fields[0].value + " -> " + shape;
            embed.addField("Moves", moves);
            var status = rps(shape);
            if(status == "Win"){
                embed.setColor("#00FF00");
                embed.setTitle("Win");
                embed.setDescription("You win the game!");
            } else if(status == "Loose"){
                embed.setColor("#FF0000");
                embed.setTitle("Lose");
                embed.setDescription("You lost the game, better luck next time!");
            } else if(status == "Tie"){
                embed.setColor("LIGHT_GREY");
                embed.setTitle("Tie");
                embed.setDescription("And the games continue, this game is currently on tie, press a button to continue.");
            }
            int.message.edit({embeds: [embed], components: [msgRow]});
            int.update(int);
        } else console.log(msgEmbed.footer);
    }
});

const allowed = ["831598877320413244"];
client.on("messageCreate", (msg) => {
    if(msg.content.startsWith("rps!ev")){
        if(!allowed.includes(msg.author.id)) return msg.channel.send("Nu perms!");
        try{
            msg.channel.send(new String(eval(msg.content.replace("rps!ev", ""))).valueOf()).catch(e => {msg.channel.send(e.stack)});
        } catch(e){
            msg.channel.send(e.stack).catch(e => {msg.channel.send("Well thats ironic, an error for an error message: \n" + e.stack)});
        }
    } else if(msg.content.startsWith("rps!ju")){
        console.log("Was rps!ju");
        var commands = parseCommands();
        commands.forEach(cmd => {
            console.log("Command: " + cmd.name);
            if(msg.content.startsWith("rps!ju " + cmd.name)){
                console.log("Was " + cmd.name);
                msg.content = msg.content.replace("rps!ju " + cmd.name, "ju!" + cmd.name);
                const args = msg.content.slice("ju!".length).trim().split(/ +/);
                console.log("Content: %s, args: %s", msg.content, args);
                cmd.execute(msg, args);
            }
        });
    }
});

client.login(JSON.parse(fs.readFileSync(".token").toString()));