const {Command,ErrorMessage, ErrorType, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, Strikes} = require('../../lib.js')
const strikeM = require('../../models/strikes');

    class strike extends Command{
        constructor(client){
            super(client, {
                name: 'removePersonalData',
                group:'admin',
                aliases: ['removeData', 'PersonalData', 'deleteMe', 'removeMe', 'forgetMe', 'forgetme'],
                description: 'Strikes an user. Usage !strike @USER REASON',
                needsAdmin:false,
            })
            this.client = client;
            this.message;
        }
        async run(message, args)
        {

            /*
            *   Use Case:
            *  1. User has strikes 
            *       -> Send a warning:
            !!*  "You have pending strikes. If you wish to proceed, strikes will resolve by kicking you out of the server."
            * 2. User has no strikes
            * 3. User is a striker
            ! "You have pending strikes. If you wish to proceed please resolve the strikes at: rem.wordfights.com. If its unavailable contact @Masterhc."
            */

            const author = message.author;
            this.message = message;
            let strokedID;
            let strikerID = strokedID = author.id;
            const Strikes = await strikeM.find({$or:[{strikerID},{strokedID} ]})
            message.delete();
            if(Strikes.length == 0) return new ErrorMessage(this.client).send(ErrorType.FullCustom, message,[`We don't have your data yet. We only store your data on strikes and for 15 days each strike. By data we mean userID and avatarID of the striker and the struck.`])
            const strikerCount = Strikes.reduce((acc, item) => 
            {
                return acc + (item.strikerID === author.id ? 1 : 0);
            },0);
                
                // Step 2: Count occurrences in strokedID
            const struckCount = Strikes.reduce((acc, item) => 
            {
                return acc + (item.strokedID === author.id ? 1 : 0);
            }, 0);
            const getStruckGuilds = (Strikes, id) => 
            {
                return Strikes.reduce((acc, item) => 
                {
                    if (item.strokedID === id) 
                    {
                        acc.push(item.guildID);
                    }
                    return acc;
                }, []);
            };
            const guilds = getStruckGuilds(Strikes, author.id);
            if(strikerCount > struckCount) return new ErrorMessage(this.client).send(ErrorType.FullCustom, message, [`You have pending strikes. Resolve the strikes you have given out, at the [dashboard](https://rem.wordfights.com 'Rem-chan Dashboard Link').`])
            else this.sendMessage("You have pending strikes. If you wish to process, the strikes will be resolved by kicking you out of the servers were you have strikes issued.", author, guilds )
        }  
        async  sendMessage(text, author, guilds)
        {
            const embed = new EmbedBuilder()
            embed.setFooter({text:'Rem-chan on ', iconURL:"https://i.imgur.com/g6FSNhL.png"})
            embed.setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'}); 
            embed.setColor(0x110809);
            embed.setTimestamp()
            embed.setTitle(`Confirmation`)    
            embed.setDescription(text)   

            const row = new ActionRowBuilder()
            .addComponents(
                new ButtonBuilder()
                    .setCustomId(`decline${author.id}`)
                    .setLabel('Decline')
                    .setStyle(ButtonStyle.Success),
                new ButtonBuilder()
                    .setCustomId(`acept${author.id}`)
                    .setLabel('Accept')
                    .setStyle(ButtonStyle.Danger),
            );
            const filter = i => i.customId.includes(author.id) ;
    
            const Message = await this.message.channel.send({ephemeral: true, embeds: [embed], components: [row] }); 
            const collector = this.message.channel.createMessageComponentCollector({ filter, time: 60000 });
            collector.on('collect', async m => 
            {
                if(m.user.id !== author.id) return m.reply({content:'You are not the requester.', ephemeral:true})
                if(m.customId.includes('decline')) return;
                collector.stop();
                m.message.delete();
                let strokedID;
                let strikerID = strokedID = author.id;
                for(let i = 0; i<guilds.length; i++)
                {
                    const Strikes = await strikeM.deleteMany({$or:[{strikerID},{strokedID} ]})
                    this.client.guilds.cache.get(guilds[i]).members.cache.get(author.id).kick();
                }
            });
            collector.on('end', async ()=>
            {
                Message.edit({ components: [] });
            })
        }
}module.exports = strike;