const {Command, Anilist, Random, ErrorMessage, ErrorType} = require('../../lib.js')

const {EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle} = require('discord.js');

  
class char extends Command{
        constructor(client){
            super(client, {
                name: 'char',
                group:'pesquisa',
                memberName: 'char',
                description: 'Shows info about a character.'

            })
        }
        async run(message, args)
        {
            if(!args[0]) return  new ErrorMessage(this.client).send(ErrorType.NoArguments, message)
            const data = await new Anilist().searchChar(args.join(' '));
            if(data=='Error') return new ErrorMessage(this.client).send(ErrorType.Arguments, message, [`Couldn't find any character with the search argument you provided.`])
            const embed = new EmbedBuilder();
            const randomID = Random();
            const row = new ActionRowBuilder();
            var fieldPayload = [];
            var embeds = [];
            for(var i = 0; i<data.length; i++)
            {
                fieldPayload.push({name:data[i].name.full+' '+(data[i].name.native?'['+data[i].name.native+']':''), value:i.toString()});
                embeds.push(new EmbedBuilder().setImage(data[i].image).setURL('https://www.rem.wordfights.com'));
                row.addComponents(
                    new ButtonBuilder()
                    .setCustomId(randomID+i)
                    .setLabel(i.toString())
                    .setStyle(ButtonStyle.Success)
                    );
            }
                row.addComponents(
                    new ButtonBuilder()
                    .setCustomId(randomID+4)
                    .setLabel('Cancel')
                    .setStyle(ButtonStyle.Danger)
                )
                embed.setTitle(`First ${data.length>=4?'4':(data.length + ' and only')} result${data.length>1?'s':''} of search:`)
                .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
                .setColor(0x003284)
                .setURL('https://www.rem.wordfights.com')
                .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
                .setTimestamp()  
                .addFields(fieldPayload);
            embeds.unshift(embed);
            // console.log(data.length, embeds.length, embeds)
            
            const filter = i => i.customId.slice(0,-1) === randomID;
            const Message = await message.channel.send({ephemeral: true, embeds, components: [row] }); 
            const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
            collector.on('collect', async m => 
            {
                message.delete();
                m.message.delete();
                if(m.customId[m.customId.length-1]!=4) sendMessage(data[m.customId[m.customId.length-1]].id);
            });
            collector.on('end', async ()=>
            {
                Message.edit({components:[]})
            })
            /**
             * @param {Number} id  
             */
            async function sendMessage(id)
            {
                const data = await new Anilist().getCharInfo(id);
                data.description = data.description.replaceAll('~!', '').replaceAll('!~', '').replaceAll(/<[^>]*>/g, '');
                data.description = data.description.length>1500?(data.description.substring(0, 1500) + "..."):data.description;
                //console.log(data)
                const embed = new EmbedBuilder()
                    .setTitle(`${data.name.full} (${data.name.native})`)
                    .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
                    .setColor(0x003284)
                    .setDescription(data.description)
                    .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
                    .setImage(data.image)
                    .setThumbnail(data.image)
                    .setTimestamp()  
                    .addFields(
                        {name:'Page', value:data.url, inline:true}
                        );
                    if(data.age) embed.addFields({name:'Age:',value:data.age, inline:true});
                    if(data.gender) embed.addFields({name:'Gender:', value:data.gender?data.gender:'', inline:true},); 
                    if(!data.name.native) embed.setTitle(`${data.name.full}`)
                    const randomID = Random();
                    const row = new ActionRowBuilder()
                    .addComponents(
                        new ButtonBuilder()
                            .setCustomId(randomID)
                            .setLabel('Remove this.')
                            .setStyle(ButtonStyle.Primary),
                    );
                    const filter = i => i.customId === randomID;
                    const sentMessage = await message.channel.send({ephemeral: true, embeds: [embed], components: [row] }); 
                    const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
                    collector.on('collect', async m => 
                    {
                        m.message.delete();
                    });
                    collector.on('end', async ()=>
                    {
                        sentMessage.edit({components:[]})
                    })
            }
        }
      


}module.exports = char;