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

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


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

            })
        }
        async run(message, args){
            if(!args[0]) return  new ErrorMessage(this.client).send(ErrorType.NoArguments, message)
            const data = await new Anilist().searchAnime(args.join(' '));
            if(data=='Error') return new ErrorMessage(this.client).send(ErrorType.Arguments, message, [`Couldn't find any anime with the search argument you provided.`])
            // console.log('SearchAnime: Data:', data[1].title.romaji, data.length);

            const embed = new EmbedBuilder()
            var embeds = [embed]
            const randomID = Random();
            const row = new ActionRowBuilder();
            var fieldPayload = [];
            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].coverImage).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);
            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 => 
            {
                collector.stop();
                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().getAnimeInfo(id);
                // console.log('Command: SearchChar: SendMessage: Data', data)
                data.description = data.description.replaceAll('~!', '').replaceAll('!~', '').replaceAll(/<[^>]*>/g, '');
                data.description = data.description.length>1500?(data.description.substring(0, 1500) + "..."):data.description;
                const embed = new EmbedBuilder()
                    .setTitle(`${data.title.romaji} (${data.title.native + (data.title.english?'/'+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)
                    .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
                    .setImage(data.coverImage)
                    .setThumbnail(data.coverImage)
                    .setTimestamp()  
                    .addFields(
                        {name:'Status:', value:data.status.replaceAll('_',' '), inline:true},
                        );
                    if(data.status!='NOT_YET_RELEASED')
                    {
                        embed.addFields(
                            {name:'Release Season:', value:data.season, inline:true},
                            {name:'Episodes:', value:data.episodes?data.episodes.toString():'N/A', inline:true}
                        );
                    }
                    embed.addFields(
                        {name:'Trailer:', value:data.trailer?(data.trailer.site=='youtube'?`https://www.youtube.com/watch?v=${data.trailer.id}`:`https://www.dailymotion.com/video/${data.trailer.id}`):'N/A'},
                        {name:'MAL Page', value:data.malLink, inline:true},
                        {name:'Anilist Page', value:data.url, inline:true}
                    )
                    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 => 
                    {
                        collector.stop();   
                        m.message.delete();
                    });
                    collector.on('end', async ()=>
                    {
                        sentMessage.edit({components:[]})
                    })
            }
        }                
                
}module.exports = anime;