const {Command, aniList, Random} = require('../../lib.js')

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

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

        })
    }
    async run(message, args)
    {
        if(!args[0]) return  new ErrorMessage(this.client).send(ErrorType.Arguments, message)
            const data = await new aniList().searchManga(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.`])
            // console.log('SearchManga: Data:', data)
            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].title.romaji+(data[i].title.english?"("+data[i].title.english+")":''), 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)
                    );
            }

            embed.setTitle(`First ${data.length>=4?'4':(data.length + ' and only')} results 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);

            const filter = i => i.customId.slice(0,-1) === randomID;
            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();
                sendMessage(data[m.customId[m.customId.length-1]-1].id);
            });
            /**
             * @param {Number} id  
             */
            async function sendMessage(id)
            {
                const data = await new aniList().getMangaInfo(id);
                const embed = new EmbedBuilder()
                    .setTitle(`${data.title.romaji} (${data.title.native} / ${data.title.english})`)
                    .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
                    .setColor(0x003284)
                    .setDescription(data.description)//.replaceAll('<br>', ' ').substring(0, 1500) + "...")
                    .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
                    .setImage(data.coverImage)
                    .setThumbnail(data.coverImage)
                    .setTimestamp()  
                    const randomID = Random();
                    const row = new ActionRowBuilder()
                    .addComponents(
                        new ButtonBuilder()
                            .setCustomId(randomID)
                            .setLabel('Remove this.')
                            .setStyle(ButtonStyle.Primary),
                    );
                    const filter = i => i.customId === randomID;
                    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();
                    }); 
            }
    }
}module.exports = manga;