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

const {EmbedBuilder, ActionRowBuilder,ButtonBuilder, ButtonStyle} = require('discord.js');
const yts = require('yt-search');
const QueueM = require('../../models/queue');

module.exports = class  play extends Command
{
    constructor(client)
    {
        super(client, {
            name: 'play',
            group:'music',
            memberName: 'play',
            description: 'Plays on the voice channel you currently are in. Supports youtube search and links.'

        })
    }
    async run(message, args)
    {
        const {voice} = message.member;
        const guild = message.channel.guild.id;
        var content = message.content;
        const channel = message.channel.id;
        const Author = message.author;
        
        try
        {
            if(!voice.channel)
            {
                console.log('Play: Err: Not currently in a voice channel.')
                message.reply('Not currently in a voice channel.')
                return
            }
            else
            {
                if(content.includes('https')||content.includes('www'))//LINK
                {
                    console.log('Play: -', Author.username,'Queued this link:',content.split('!play')[1],'on',message.channel.guild.name,"'s", message.channel.name)
                    
                    if(content.includes('youtube') || content.includes('youtu.be'))//YT LINK
                    {
                        console.time('SearchL')
                        if(!isPlayList(content))
                        {
                            content = content.split('&time=')?content.split('&time=')[0]:content;
                            content = content.split('&ab_channel=')?content.split('&ab_channel=')[0]:content;
                            const r = await yts( content.split('!play ')[1] )
                            console.timeEnd('SearchL')
                            addToQ(r.videos[0]);
                            message.delete()
                        }
                        else
                        {
                            try 
                            {
                                
                                var listID
                                if(content.split('&list=')[1].includes('&'))
                                {
                                    listID = content.split('&list=')[1].split('&')[0]
                                }
                                else listID = content.split('&list=')[1]
                                console.log('Play: List: ListID:',listID)
                                const list = await yts({listId:listID})
                                list.videos.forEach(video=>
                                    {
                                        //console.log('Teste: PlayList: ForEach(video): video:', video)
                                        addToQ(video)
                                    })
                                message.delete();
                            } 
                            catch (error) 
                            {
                                console.log('Play: List: Error:', error)
                            }
                        }
                    }
                    else //GET OUTTA HERE
                    {
                        message.channel.send('Either use a link from youtube or try searching by keywords.')
                    }
                }
                else//search
                {
                    console.log('Play: Searching for:', content.split('!play')[1])
                    const r = await yts(content.split('!play ')[1])       
                    const videos = r.videos.slice( 0, 3)
                    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.setTimestamp();
                    embed.setColor(0xb50000);
                    embed.setTitle('Searching for:'+ args.join(' '))
                    embed.setImage(videos[0].thumbnail)
                    const row = new ActionRowBuilder();
                    const randomID = Random();
                    videos.forEach( function ( v , i) {
                        //console.log('Search:', v)
                        const views = String( v.views ).padStart( 10, ' ' )
                        embed.addFields( {name:`[ ${i} ] - ${ v.title }`,value:`${ v.author.name } |  (${v.timestamp }) | ${ views } views`} )
                        row.addComponents(
                            new ButtonBuilder()
                                .setCustomId(`${randomID}PlayUserChoice${i}`)
                                .setLabel(` ${i} `)
                                .setStyle(ButtonStyle.Primary),
                        );
                    } )
                    embed.addFields({name:'Cancel', value:'Press X'});
                    row.addComponents(
                        new ButtonBuilder()
                            .setCustomId(`${randomID}PlayUserChoice`)
                            .setLabel(` X `)
                            .setStyle(ButtonStyle.Danger),
                    );
                    const Message = await message.channel.send({ephemeral: true, embeds: [embed], components: [row] }); 
                    
                    const filter = i => i.customId.startsWith(`${randomID}PlayUserChoice`);
                    const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
                    collector.on('collect', async m => 
                    {
                        // console.log(m)
                        collector.stop();
                        message.delete();
                        m.message.delete();
                        if(m.customId != 'PlayUserChoice')
                        {                          
                            addToQ(videos[parseInt(m.customId.split(`${randomID}PlayUserChoice`)[1])])
                        }
                    });
                    collector.on('end', async ()=>
                    {
                        Message.edit({ components: [] });
                    })
                }
            }
            
            function isPlayList(content)
            {
                if(content.includes('&list='))
                {
                    return true;
                }
                else return false;
            }
            function addToQ(video)
            {
                
                var queueItem = new QueueM();
                queueItem.songname = video.title;
                queueItem.songtime = video.seconds||video.duration.seconds;
                queueItem.songURL = video.url||'https://youtube.com/watch?v='+video.videoId
                queueItem.guild = guild;
                queueItem.textchannel = channel;
                queueItem.voice = voice.channel.id;
                queueItem.requester = Author.username;
                queueItem.save(err=>
                {
                    if(err)console.error(err)
                    //console.log('Play: Search: Item added to queue:', queueItem)
                })
            }
        } catch (error) {
            console.log('Play: Error:', error);
        }
    }
}