const {Command, Random, ErrorMessage, ErrorType} = require('../../lib.js')
const {EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle} = require('discord.js');
const xmlparser = require('xml-js')
const feedM = require('../../models/feeds');
class setYTFeed extends Command{
    constructor(client){
        super(client, {
            name: 'setFeed',
            aliases:['setYTFeed','setytf', 'setYTF'],
            description: 'Sets the message channel where a defined youtube channel feed will be displayed. (Order: Youtube channel url, discord channel id, Costum message to display when a new video is released)',
            needsAdmin:true,
        });
        this.client = client;
    }
    async run(message, args)
    {       

        // Validate the command arguments
        const validationResult = await this.confirmArgs(message, args);
        if (validationResult.error) return new ErrorMessage(this.client).send(ErrorType.Arguments, message, [validationResult.error])
        var feed = new feedM();
        feed.gID = message.guildId;
        feed.ChannelId = validationResult.channelId
        feed.YTChannelId = validationResult.YTChannelId;
        feed.CostumMessage = args[3]?args.splice(2).join(' '):'New video:';
        feed.save(err=>
            {
                if(err)console.log(err);
            })
        const embed = new EmbedBuilder()
        const randomID = Random();
        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.setColor(0x110809);
        embed.setTimestamp()
        embed.setTitle(`${validationResult.name}'s feed defined on channel ${validationResult.channelName}.`)
        if(args!='New video:') embed.setDescription(`With the costum message: \n ${feed.CostumMessage}`)

        const row = new ActionRowBuilder()
        .addComponents(
            new ButtonBuilder()
                .setCustomId(randomID)
                .setLabel('Remove this.')
                .setStyle(ButtonStyle.Primary),
        );
        const filter = i => i.customId === randomID;
        message.channel.send({embeds: [embed], components: [row] }); 
        const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
        collector.on('collect', async m => 
        {
            _delete(message, m);
        });
        collector.on('end', async m=>
        {
            _delete(message,m);
        })   
    }
   

    /**
     * 
     * @param {Map<String,String>} message 
     * @param {Array<String>} args 
     * @returns {RoleModel}
     * 
     */
    async confirmArgs(message,args)
    {
        if(args.length<2) return {error:'Unsuficient amount of arguments.'}
        var channelURL = args[0];
        var YTChannelId = await getChannelId(channelURL);
        if(!YTChannelId) return {error:'Provided Youtube channel does not exist.'};
        var channelId = args[1];
        const exists = await this.client.channels.fetch(channelId).then(channel=>{return channel }).catch(()=>{return });
        if(!exists) return {error:'Provided channel id does not exist.'}   
        var name = await fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${YTChannelId}`)
                            .then(handleResponse)
                            .then(handleData)
                            .catch(handleError);
                            function handleResponse(response) 
                            {
                            return response.text()
                            }
                            function handleError(error) 
                            {
                            return error;
                            }
                            function handleData(data) 
                            {
                                data = xmlparser.xml2json(data,
                                                {
                                                    compact: true,
                                                    space: 4
                                                });
                                data = JSON.parse(data);
                                return data.feed.author.name._text
                            }  
        if(!name) return {error:'Provided Youtube channel does not exist.'}   
        return {YTChannelId, channelId, name, channelName:exists.name}
    }
    
}module.exports = setYTFeed;

function _delete(message, m)
{
    try {
        message.delete();
        m.message.delete();
    } catch (error) {
        console.log('SetYTID: Error deleting the message:',error)
    }
}

async function getChannelId(url)
{
    if(url.split('@').length<1) return false
    return await fetch(url)
            .then(handleResponse)
            .then(handleData)
            .catch(handleError);
            function handleResponse(response) 
            {
                if(response.ok) return response.text();
            }
            function handleError(error) 
            {
                return error;
            }
            function handleData(data) 
            {          
                return data ? data.split('https://www.youtube.com/feeds/videos.xml?channel_id=')[1].split('"')[0] : false;
            }
}