const {Command, ErrorMessage, ErrorType, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, Random} = require('../../lib.js')


    class  poll extends Command{
        constructor(client){
            super(client, {
                name: 'poll',
                memberName: 'poll',
                description: `Make a poll of what ever you want. Usage: !poll QUESTION? "OPTION1" "OPTION2" "OPTION3"; Be sure to add the quotation marks on the options.`

            })
            this.client = client;
        }
        async run(message, args)
        {
            if(!args.some(arg=>arg.includes('?'))) return new ErrorMessage(this.client).send(ErrorType.Arguments, message,['There is no question on the poll.'])
            args = args.join(' ').split('?');
            const Question = args[0]+'?';
            args.shift();
            args = args[0].replace(/(?<=^|")\s+|\s+(?="|$)/g, '')
            if(!hasEvenQuotes(args)) return new ErrorMessage(this.client).send(ErrorType.Arguments, message, ['The options must be sent in between quotation marks. ("option")']);
            args = args.split('""');
            var options = [];
            for(var arg of args)
            {
                options.push(arg.replace('"', ''));
            }
            sendMessage(message, Question, options);

        }
    }
    module.exports = poll;
function hasEvenQuotes(str) 
{
    let count = 0;
    for (let i = 0; i < str.length; i++) 
    {
        if (str[i] === '"') 
        {
        count++;
        }
    }
    return count % 2 === 0;
}

async function sendMessage(message, Question, options)
        {
            var fields = [];
            var buttons = new ActionRowBuilder();
            const randomID = Random();
            for(var [index, option] of options.entries())
            {
                fields.push({name:option, value:'Votes: 0', inline:false});
                buttons.addComponents(new ButtonBuilder()
                            .setCustomId(randomID+index)
                            .setLabel(index.toString())
                            .setStyle(ButtonStyle.Success)
                    )
            }
            // console.log(fields, buttons);
            const embed = new EmbedBuilder()
                .setTitle(`${Question.charAt(0).toUpperCase() + Question.slice(1)}`)
                .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
                .setColor(0x0fff87)
                .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
                .setTimestamp()  
                .addFields(fields)
            const filter = i => i.customId.slice(0,-1) === randomID;
            const sentMessage = await message.channel.send({ephemeral: true, embeds: [embed], components: [buttons]}); 
            const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
            var repliers= []
            collector.on('collect', async m => 
            {
                if(repliers.includes(m.user.id)) return m.reply({content: 'You have already answered the poll.', ephemeral:true});
                repliers.push(m.user.id);
                var index = m.customId[m.customId.length-1];
                var prevValue = parseInt(embed.data.fields[index].value.match(/\d+/)[0]);
                embed.data.fields[index].value ='Votes: '+(prevValue+1);
                m.update({embeds: [embed]});
            }); 
            collector.on('end', async ()=>
            {
                sentMessage.edit({components:[]})
            })
        }