const { Events, MessageFlags, Message } = require('discord.js')
const { mClient } = require('../index')
require('dotenv').config()

module.exports = {
    name: Events.InteractionCreate,
    once: false,
    async execute(interaction) {
        if (interaction.isChatInputCommand()) { commandHandler(interaction) }
        if (interaction.isButton()) { buttonHandler(interaction) }
        if (interaction.isMentionableSelectMenu()) { selectMenuHandler(interaction) }
        if (interaction.isUserSelectMenu()) { selectMenuHandler(interaction) }
        if (interaction.isModalSubmit()) { modalSubmitHandler(interaction) }
    }
}
async function commandHandler(interaction) {
    const command = interaction.client.commands.get(interaction.commandName);

    if (!command) {
        console.error(`No command matching ${interaction.commandName} was found.`);
        return;
    }
    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        if (interaction.replied || interaction.deferred) {
            await interaction.followUp({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
        } else {
            await interaction.reply({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
        }
    }
}
async function buttonHandler(interaction) {
    const button = interaction.client.buttons.get(interaction.customId)
    if (!button) { return }// console.error(`No button registered matching ${interaction.customId}.`) }
    try {
        await button.execute(interaction);
    } catch (error) {
        console.error(error);
        if (interaction.replied || interaction.deferred) {
            await interaction.followUp({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
        } else {
            await interaction.reply({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
        }
    }
}
async function selectMenuHandler(interaction) {
    const selectMenu = interaction.client.selectMenus.get(interaction.customId)
    if (!selectMenu) { return console.error(`No Select Menu registered matching ${interaction.customId}.`) }
    try {
        await selectMenu.execute(interaction);
    } catch (error) {
        console.error(error);
        if (interaction.replied || interaction.deferred) {
            await interaction.followUp({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
        } else {
            await interaction.reply({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
        }
    }
}
async function modalSubmitHandler(interaction) {
    if (interaction.customId === 'wgeBaseModal') {
        const db = mClient.db('neo-db')
        const wgeColl = db.collection('timer_wge')
        const participateColl = db.collection('items_wge')

        // Get the data entered by the user

        var wgeAssignedUser = {}
        wgeAssignedUser.id = interaction.components[0].component.values[0]

        const wgeAssigningUser = interaction.user
        if (wgeAssignedUser.id === process.env.D_ID) {
            // Randomizer Function
            const randomParticipant = await participateColl.aggregate([
                { $match: { status: true } },
                { $sample: { size: 1 } }
            ]).toArray()

            if (!randomParticipant) { return interaction.followUp({ content: 'No User is participating!' }) }

            random = await interaction.guild.members.fetch(randomParticipant[0].userID)
            wgeAssignedUser = random.user
        } else {
            // validate non-random user
            const foundParticipant = await participateColl.findOne({
                $and: [
                    { assignedUser: wgeAssignedUser.id },
                    { status: true}
                ]
            })

            if(!foundParticipant || foundParticipant == null){ return interaction.reply({
                content: `<@${wgeAssignedUser.id}> is not participating!`,
                flags: MessageFlags.Ephemeral
            })}
        }


        const prevWge = await wgeColl.findOne({
            $and: [
                { debug: false },
                { state: 'running' }
            ]
        })

        if (prevWge != null) {
            // Save previous run in history_wge
            const historyWgeColl = db.collection('history_wge')
            await historyWgeColl.insertOne({
                assignedUser: prevWge.assignedUser,
                assigningUser: prevWge.assigningUser,
                timeRemaining: prevWge.timeRemaining,
                topic: prevWge.topic,
                debug: prevWge.debug,
                createdAt: prevWge.createdAt
            });

            console.log({
                message: 'saved previous wge in history_wge',
                data: prevWge
            })

            await wgeColl.deleteOne({
                _id: prevWge._id
            })
        }

        const wgeAssignedTopic = interaction.fields.getTextInputValue('wgeTopicInput');

        const wgeDefaultAssignedTime = 7 * 24 * 60 * 60 * 1000; // 7 days in ms

        await wgeColl.insertOne({
            assignedUser: wgeAssignedUser.id,
            assigningUser: wgeAssigningUser.id,

            startedAt: Date.now(),
            timeRemaining: wgeDefaultAssignedTime,

            state: 'running',

            notifications: {
                half: false,
                day24: false,
                complete: false
            },

            topic: wgeAssignedTopic,
            debug: false,

            createdAt: new Date()
        });

        return interaction.reply({ content: `<@${wgeAssignedUser.id}> is the next expert! Their topic is **${wgeAssignedTopic}**` })
    }
}