const { Client, Intents, MessageAttachment, MessageEmbed } = require('discord.js');
const client = new Client({ intents: [
	Intents.FLAGS.GUILDS,	
	Intents.FLAGS.GUILD_MESSAGES, 
	Intents.FLAGS.GUILD_MESSAGE_REACTIONS
] });

/**
    List of intents
    https://discord.com/developers/docs/topics/gateway#privileged-intents
*/

require("dotenv").config()

var hugGifs =
        ["https://c.tenor.com/9e1aE_xBLCsAAAAC/anime-hug.gif",
         "https://c.tenor.com/Ct4bdr2ZGeAAAAAC/teria-wang-kishuku-gakkou-no-juliet.gif",
         "https://c.tenor.com/ztEJgrjFe54AAAAd/hug-anime.gif",
         "https://c.tenor.com/UhcyGsGpLNIAAAAd/hug-anime.gif",
         "https://c.tenor.com/fLxZt7jo1YEAAAAd/loli-dragon.gif",
         "https://c.tenor.com/qF7mO4nnL0sAAAAd/abra%C3%A7o-hug.gif"]

client.once('ready', () => {
    console.log('Running');
});

client.on("messageCreate", gotMessage);

function gotMessage(message){

    if(message.content.includes('https://media.discordapp.net') &&
        message.content.includes('webm') || message.content.includes('mov') ||
        message.content.includes('mp4')) {
        const linkArr = message.content.split('https://media.discordapp.net');
        message.channel.send('https://cdn.discordapp.com' + linkArr[1])
    }

    const msg = message.content.toLowerCase()

    const content = message.content.trim()

    let msgContentSplit = content.split(/[ ]+/);

    /**
     * reference can't be null => must be a reply to message
     * must contain only one argument
     * that argument mentions channel
     */

    if(message.reference != null && msgContentSplit.length == 1
        && message.mentions.channels.first() != undefined){
        move(message, msgContentSplit[0])
    }

    const isBot = message.author.bot

    if (!isBot){
        if (msg.includes("henlo")) {
            henlo(message);
        }
        else if (msg.includes("how ye")) {
            mood(message)
        }
        else if (msg.includes("tylko jedno")) {
            message.channel.send("Koksu pięć gram odlecieć sam");
        }
        if (msgContentSplit[0] == "hug") {
            hug(message)
        }
        else if (msgContentSplit[0] == "!say") {
            say(message);
        }
    }
}

// Responses
function henlo(message){
    var emojis = ["🥰", "🐄", "🐮", "❤️", "👋", "🤠", "😊"];
    let randomNum = RNG(emojis.length);
    message.reply("Henlooo " + message.author.username + "   " + emojis[randomNum]);
}

function hug(message){
    var mentionedUsers = message.mentions.users.values()
    var mentionedUsersSize = message.mentions.users.size
    var mentionedRoles = message.mentions.roles.values()
    var mentionedRolesSize = message.mentions.roles.size

    var msg = message.content.toLowerCase()

    let randomNum = RNG(hugGifs.length)
    let title = message.author.username + " hugs"
    let embed;
    if (mentionedUsersSize > 0 || mentionedRolesSize > 0){
        let allMentions = ""
        for (let i = 0; i < mentionedUsersSize; i++) {
            let user = mentionedUsers.next()
            allMentions = allMentions + ", <@" + user.value.id + ">"
        }
        for (let i = 0; i < mentionedRolesSize; i++) {
            let role = mentionedRoles.next()
            allMentions = allMentions + ", <@&" + role.value.id + ">"
        }
        allMentions = allMentions.slice(2)
        embed = createEmbed(title, hugGifs[randomNum], allMentions)
    }
    else if (msg.includes("@here") || msg.includes("all")){
        embed = createEmbed(title, hugGifs[randomNum], "@here")
    }
    else if (msg.includes("@everyone")){
        embed = createEmbed(title, hugGifs[randomNum], "@everyone")
    }
    else {
        embed = new MessageEmbed().setImage(hugGifs[randomNum]).setColor(randomColor())
    }
    message.channel.send({embeds: [embed]})
}

function mood(message){
    var responses = ["Not bad, how yee?", "MOOdy", "A bit sad 😢", "Good, how yee?", "I'm fine, how yee?"];
    let randomNum = RNG(responses.length);
    message.reply(responses[randomNum]);
}

function move(message, channelId){
    message.react('🐮')
    
    const replyChannel =  message.channel;

    // const replyChannelId =  message.reference.channelId;
    // const replyChannel = client.channels.cache.get(replyChannelId);
    
    const msgToMooveId = message.reference.messageId;
    
    const mentionedChannelId = channelId.substring(2, channelId.length - 1)
    

    // create embed
    // add field for every attachment
    //  keď je tam emebed tak možnosť cez emotes či vymazať original post alebo nie
    replyChannel.messages.fetch(msgToMooveId).then(msg => {
        
        
        if (msg.attachments.size > 0){
            // var exampleEmbed = new MessageEmbed()
            //     .setTitle('Some title')
            //     .setImage(allAttachments.next().value)
            //     .addField('Inline field title', 'Some value here', true);
            //     .addField("Original message: ", message.content)
            let newMsgAttachments = []
            let allAttachments = msg.attachments.values()
        
            for (let i = 0; i < msg.attachments.size; i++){
                let currAttachment = allAttachments.next().value
                newMsgAttachments.push(new MessageAttachment(currAttachment.url))
            }

            client.channels.cache.get(mentionedChannelId).send({files: newMsgAttachments}).then(msgToEdit => {
                msgToEdit.edit(`Sent by ${msg.author}\nmooved ${message.author}\n`)
            })
            setTimeout(() => msg.delete(), 3000);
        }
        else {
            if (msg.embeds.length > 0){
                message.channel.send("Can't really moove embeds yet, sowwy :c")
            }
            else {
                const embed = new MessageEmbed()
                                .setColor(randomColor())
                                .addField("MOO", `Sent by ${msg.author}\nmooved ${message.author}`)
                                .addField("Message:", msg.content)
                client.channels.cache.get(mentionedChannelId).send({embeds: [embed]})
                setTimeout(() => msg.delete(), 3000);
            }
        }
    });
    setTimeout(() => message.delete(), 3000);
}

function say(message){
    const tmp = message.content.split("!say ");
    const msgContent = tmp[1];
    const msgChannel = message.channel;
    message.delete()
    if (msgContent != undefined && msgContent != ""){
        msgChannel.send(msgContent);
    }
}

function createEmbed(title, img, desc){
    let embed = new MessageEmbed()
            .setTitle(title)
            .setImage(img)
            .setDescription(desc)
            .setColor(randomColor())
    return embed
}

function randomColor() {
    let color = '#';
    for (let i = 0; i < 6; i++){
       const random = Math.random();
       const bit = (random * 16) | 0;
       color += (bit).toString(16);
    };
    return color;
 };

function RNG(max){
    return Math.floor(Math.random() * max)
}

// narodeniny?
// vianoce, novy rok a tak
// hug cez tenor
// headpat cez tenor
// .gif
client.login(process.env.TOKEN)
