const { SlashCommandBuilder, EmbedBuilder, DefaultWebSocketManagerOptions, discordSort } = require("discord.js");
const { __glob } = require("../modules/global-variables");
const { LogType } = require("loguix");
var { List } = require("./sub-list")
const discord = require("./discord-bot")
var ytfps = require("ytfps");
const packageJson = require(__glob.PACKAGE);
const { Metric } = require("webmetrik");

const list = new List()

module.exports.getSong = async function (url) {
    var client = discord.getClient()
    const songs = await client.manager.search(url)
    return songs.tracks[0]
}

module.exports.play = async function (client, interaction) {

    if(interaction) {

        let player = client.manager.players.get(interaction.guild.id)

        const song_name = interaction.options.getString("nom_ou_lien")
    
        if(!player) { 
            
            player = client.manager.create({
                guild: interaction.guild.id,
                voiceChannel: interaction.member.voice.channel.id,
                textChannel: interaction.channel.id,
            });


            player.connect();
        }

        // CHECK OF PLAYLIST


        var playlist = await checkPlaylist(song_name)


        if(playlist) {

            list.playlistAdd(playlist, interaction)

        } else {

            const songs = await client.manager.search(song_name)

            if(songs.tracks.length == 0) {
                const embed = await new EmbedBuilder()
                .setColor(0xff0000)
                .setTitle('*On connait pas le morceau !*')
                .setTimestamp();
    
                interaction.reply({embeds: [embed], ephemeral: true})

            } else {

                if(!player.playing) {
              
                    player.play(songs.tracks[0])
        
                    const embed = await new EmbedBuilder()
                    .setColor(0x15e6ed)
                    .setTitle('**Lecture de : **' + songs.tracks[0].title)
                    .setDescription('**Demandé par **' + interaction.member.user.username)
                    .addFields({name: "Auteur", value: songs.tracks[0].author},
                               {name: "URL", value: songs.tracks[0].uri})
                    .setThumbnail(songs.tracks[0].thumbnail)
                    .setTimestamp();
        
                    interaction.reply({embeds: [embed]})
                } else {
    
                    list.add(songs.tracks[0], interaction)
                    
                }
               
            }

          
            
        }

        playStats(interaction.member.user.username)

    } 

   
    process.emit("MUSIC_UPDATE_STATE")
        
}


module.exports.pause = function (client, interaction) {

    if(interaction) {

        let player = client.manager.players.get(interaction.guild.id)

        if(player) {

            if(player.playing) {
                
                const embed = new EmbedBuilder()
                .setColor(0x03ff2d)
                .setTitle('Pause !')
                .setDescription("**Ok, une entracte est demandée par " + interaction.member.user.username + "**")
                .setTimestamp();

            
                interaction.reply({embeds: [embed]})
     
                player.pause(true)
            } else {
              
                const embed = new EmbedBuilder()
                .setColor(0x03ff2d)
                .setTitle('C\'est reparti !')
                .setDescription("**Ok, Fin de l'entracte, c'est reparti et c'est demandée par " + interaction.member.user.username + "**")
                .setTimestamp();

            
                interaction.reply({embeds: [embed]})
               
                player.pause(false)
            }

        } else {

            interaction.reply("**Aucune musique n'est actuellement jouée !**")
        }

    } else {

        if(!client) {

            client = discord.getClient()
        }

        let player = client.manager.players.get("137291455336022018")

        if(player) {

            if(player.playing) {
                player.pause(true)
            } else {

                player.pause(false)
            }

        }


    }

    process.emit("MUSIC_UPDATE_STATE")

}

module.exports.getState = function(client, interaction) {

    if(interaction) {
        let player = client.manager.players.get(interaction.guild.id)

        if(player) {

        let embed = new EmbedBuilder()
        .setColor(0x32a875)
        .setTitle('Information sur la musique')
        .addFields({name:"Titre", value: player.queue.current.title},
                   {name:"Auteur", value: player.queue.current.author},
                   {name:"URL", value: player.queue.current.uri})
        .setTimestamp()
        .setThumbnail(player.queue.current.thumbnail);

        interaction.reply({embeds: [embed]})
        
        } else {

            interaction.reply("**Aucune musique n'est actuellement jouée !**")
        }

    } else {
              // [A FINIR POUR WEB]

    }

   
        
}

module.exports.playPlaylist = function (id, data, quick) {

    
    const playlist = {}
    playlist.videos = data
    list.playlistAdd(playlist, null, id, quick)


}


module.exports.addSong = async function (data, userId, quick, playlist) {



    var client = discord.getClient()
    
    let player = client.manager.players.get("137291455336022018")

    var memberVoices = discord.getMemberVoices()
    var channelId = memberVoices.get(userId)

    if(!channelId) {
        
        channelId = "664355808250953739"
    }

    if(!player) { 
            
        player = client.manager.create({
            guild: "137291455336022018",
            voiceChannel: channelId,
            textChannel: "664355637685256203",
        });


        player.connect();
    }


    var songs = null

    if(playlist) {
       songs = await client.manager.search(data)

    } else {

        songs = await client.manager.search(data.uri)
    }

    if(quick) {
        
        player.play(songs.tracks[0])

        if(list.getCurrent()) {

            list.__previous_add(list.getCurrent())
        }
    } else {

        if(!player.playing && player.paused == false) {

            player.play(songs.tracks[0])
    
        } else {
            
            list.add(songs.tracks[0])
    
        }
    }

   

    process.emit("MUSIC_UPDATE_STATE")

}

module.exports.addSongsFromPlaylist = async function (data, userId, quick) {

   

    var playlist = await checkPlaylist(data)

    if(playlist) {
        if(quick) {
            list.removeAll()
            list.playlistAdd(playlist, null, userId, true)
        } else {
            list.playlistAdd(playlist, null, userId)
        }
        

    } 

   

    process.emit("MUSIC_UPDATE_STATE")

}

module.exports.skip = function (client, interaction) {

    if(interaction) {

        let player = client.manager.players.get(interaction.guild.id)

        if(player) {
            if(!list.haveSongs()) {

                var embed = new EmbedBuilder()
                .setColor(0xff0303)
                .setTitle('Erreur : Skip')
                .setTimestamp();
                const song_show = {name: "Aucune chanson n'est dans la queue", value: "Changement impossible !"}
                    
                embed.addFields(song_show)
                interaction.reply({embeds: [embed]})
            } else {
            
         
    
                var embed = new EmbedBuilder()
                .setColor(0x03ff2d)
                .setTitle('On change de morceau !!!')
                .setDescription("**Ok, On est reparti avec "+ list.getNextSong().title + " et c'est demandée par " + interaction.member.user.username + "**")
                .setThumbnail(list.getNextSong().thumbnail)
                .setTimestamp();

                player.stop()
                
                interaction.reply({embeds: [embed]})
                
            }
        } else {

            interaction.reply("**Aucune musique n'est actuellement jouée !**")
        }

        
    } else {

        if(!client) {

            client = discord.getClient()
        }

        let player = client.manager.players.get("137291455336022018")

        if(player) {

            player.stop()

        }

    
        

       
    }

    process.emit("MUSIC_UPDATE_STATE")
}

module.exports.seek = function (data) {

  

    client = discord.getClient()
    

    let player = client.manager.players.get("137291455336022018")

    if(player) {

        player.seek(data)

    }


    process.emit("MUSIC_UPDATE_STATE")



}

module.exports.setVol = function (data) {

  

    client = discord.getClient()
    

    let player = client.manager.players.get("137291455336022018")

    if(player) {

        player.setVolume(data)

    }


    process.emit("MUSIC_UPDATE_STATE")



}

module.exports.loop = function (client) {

    
    if(!client) {

        client = discord.getClient()
    }

    let player = client.manager.players.get("137291455336022018")

    if(player) {

        if(player.queueRepeat == true) {
            player.setQueueRepeat(false)
        } else {

            player.setQueueRepeat(true)
        }

    }

    process.emit("MUSIC_UPDATE_STATE")

} 

module.exports.changeShuffle = function (client) {

    const shuffle = list.getShuffle()

    if(!client) {

        client = discord.getClient()
    }

    let player = client.manager.players.get("137291455336022018")

    if(player) {

        if(shuffle == true) {
            list.setShuffle(false)
        } else {

            list.setShuffle(true)
        }

    }

    process.emit("MUSIC_UPDATE_STATE")

}

const slog = new LogType("Search")

module.exports.search = async function (data, client) {

    var answer = {
        "results":null,
        "playlist":false
    }

    if(!client) {

        client = discord.getClient()
    }

    slog.log("Recherche avec les mots clés : " + data)

    var splaylist = await checkPlaylist(data)


    if(splaylist) {
        answer.playlist = true
        answer.results = splaylist

    } else {

        const songs = await client.manager.search(data)
        answer.playlist = false
        answer.results = songs
    }

    return answer

    

   
}




module.exports.previous = function (client, interaction) {

    if(interaction) {

        let player = client.manager.players.get(interaction.guild.id)

        if(player) {

            if(!list.havePreviousSongs()){

                embed = new EmbedBuilder()
                .setColor(0xff0303)
                .setTitle('Erreur : Back')
                .setTimestamp();
                const song_show = {name: "Aucune chanson n'a été joué précédemment !", value: "Changement impossible !"}
                    
                embed.addFields(song_show)
                interaction.reply({embeds: [embed]})
            } else {

                list.__next_add(player.queue.current)
                player.play(list.previous())


                embed = new EmbedBuilder()
                .setColor(0x03ff2d)
                .setTitle('Retour vers le passé !!!')
                .setDescription("**Ok, On est reparti avec "+ player.queue.current.title +" et c'est demandée par " + interaction.member.user.username + "**")
                .setTimestamp();

                

            
                interaction.reply({embeds: [embed]})
                
            } 

        }

    } else {

        if(!client) {

            client = discord.getClient()
        }

        let player = client.manager.players.get("137291455336022018")

        if(list.havePreviousSongs()){
            list.__next_add(player.queue.current)
            player.play(list.previous())
        } 

       
    }
    process.emit("MUSIC_UPDATE_STATE")
}

const clog = new LogType("Actualisation")

module.exports.report = async function (client, interaction, data) {

    if(!client) {

        client = discord.getClient()
    }

    var level = null
    var desc = null

    if(interaction) {

        level = interaction.options.getString("level")
        desc = interaction.options.getString("desc")
    } 

    if(data) {
        level = data.level
        desc = data.desc

    }

  

    var embed = new EmbedBuilder()
        .setDescription('**Version **' + packageJson.version)
        .setTimestamp();

    if(interaction) {

        embed.setTitle('Report de ' + interaction.member.user.username )
    }

    if(data) {
        embed.setTitle('Report de ' + data.username.user.username )
        
    }

    var levelString = null

    if(level == "Majeur") {

            levelString = "Urgent"
            embed.setColor(0xc20f02)
    } else if(level == "Mineur") {
            levelString = "Mineur"
            embed.setColor(0xdcff17)
            
    } else {
            levelString = "Suggestion"
            embed.setColor(0xffffff)
          
    }

    embed.addFields({name: "Niveau", value: levelString},{name: "Description", value: desc})

    const channel = await client.channels.fetch('1102177962817749033')

    channel.send({embeds: [embed]})
    channel.send({content: "<@486943594893017119>"})

    if(interaction) {

        const membed = new EmbedBuilder()
        .setColor(0x00ff66)
        .setTitle('Rapport de Bug envoyé !')
       
        interaction.reply({embeds: [membed]})
    }

        

}

module.exports.updateMusicState = function (client, action) {
    

    if(!client) {

        client = discord.getClient()
    }

    let player = client.manager.players.get("137291455336022018")
    var currentTitle = "null"

    const data = {
        "playing": 0,
        "current":null,
        "isOnline": false,
        "queue": null,
        "shuffle": false,
        "loop": false,
        "durationNow": null,
        "durationAll": null,
        "volume": null
    }

    if(player) {

        
        const shuffle = list.getShuffle()

        if(shuffle) {

            data["shuffle"] = true
        }

        data["current"] = player.queue.current
  
        if(player.queueRepeat == true) {

            data["loop"] = true
        } 

        data["volume"] = player.volume * 10
        

        if(player.queue.current) {
            data["durationNow"] = player.position
            data["durationAll"] = player.queue.current.duration
            currentTitle = player.queue.current.title
        } 
        

        if(player.playing == true && player.paused == false) {

            data["playing"] = 1
        } else {
            data["playing"] = 0

        }

        data["queue"] = list.getList();
        
        data["isOnline"] = true
       
    }  

    data["previous"] = list.getPreviousList();

    if(action == "end") {

        data["current"] = null;
        data["isOnline"] = false
    }

    clog.log("Actualisation Clients - Titre : " + currentTitle + " - Loop : " + data.loop + " - Shuffle : " + data.shuffle + " - Playing : " + data.playing + " - Volume : " + Math.trunc(data.volume / 10) )
    return data

    
}

// FINI

module.exports.leave = function (client, interaction) {

    
    var player = null
    
    if(interaction) {

        player = client.manager.players.get(interaction.guild.id)
    } else {

        client = discord.getClient()
        player = client.manager.players.get("137291455336022018")

    }
        
    if(player) {

        player.destroy()


        if(interaction) {

            const embed = new EmbedBuilder()
            .setColor(0xff0000)
            .setTitle('C\'est tout pour nous !')
            .setDescription("**Le meilleur groupe du monde est parti ... !**")
            .setTimestamp();

            
            interaction.reply({embeds: [embed]})

        }
       

    } else {

        
        if(interaction) {

            interaction.reply("**Aucune musique n'est actuellement jouée !**")
        }

       
    }

    process.emit("MUSIC_UPDATE_STATE")

    
}


module.exports.moveOut = function(userId) {
    var memberVoices = discord.getMemberVoices()
    var channelId = memberVoices.get(userId)

    console.log(channelId)

    if(channelId) {
        
        var client = discord.getClient()
        var player = client.manager.players.get("137291455336022018")
        if(player) { 
                   
            player.voiceChannel = channelId
            player.connect()
           
        }
    }

}

// FINI

async function checkPlaylist (song_name) {
    
    try {

        return await ytfps(song_name)

    } catch(err) {

        return false
    }

}




function playStats(username) {
    var userMusicPlayed = new Metric("userMusicPlayed_" + username, "Nombre de musiques jouées par l'utilisateur : " + username)
    userMusicPlayed.setValue(userMusicPlayed.getValue() + 1)
    
}