const { SlashCommandBuilder, EmbedBuilder } = require("discord.js");
const { __glob } = require("../modules/global-variables");
const { LogType } = require('loguix');
const discord = require("./discord-bot")
const fs = require('fs')

const dlog = new LogType("Queue-List")

/// <reference path="./types.d.ts" />

var next = new Array()
var current = null;
var shuffle = false

if(!fs.existsSync(__glob.PREVIOUS_FILE)) {
    fs.writeFileSync(__glob.PREVIOUS_FILE, JSON.stringify(new Array(), null, 2))
}

module.exports.List = class {

    getList() {
        return next
    }

    getPreviousList() {
        return getPreviousFile()
    }

    getCurrent() {
        return current
    }
    
    removeAll() {
        next = new Array()
        process.emit("MUSIC_UPDATE_STATE")
    }

    destroy() {

        next = new Array()
        current = null
        shuffle = false
    }

    playQueue(data) {
        // Play the song with the index in the queue and delete it from the queue

        var index = data[0]
        var list = data[1]

        if(list == "next") {

            const song = next[index]
            next.splice(index, 1)
     
            return song
        } else if(list == "previous") {
   
            const song = getPreviousFile()[index]
        
            return song

        }

    }

    changeQueue(index) {
        //PREVIOUS TO NEXT

        const song = getPreviousFile()[index]
        next.push(song)

        process.emit("MUSIC_UPDATE_STATE")

    }   

    setShuffle(state) {
     
        shuffle = state

    }

    getShuffle() {

        return shuffle
    }

    next() {

        if(!shuffle) {
            const song = next[0]
            next.splice(0, 1)
            return song
           
        } else {
            const randomIndex = Math.floor(Math.random() * next.length);
            const song = next[randomIndex]
            next.splice(randomIndex, 1)
            return song
            
        }

  
       
    }

    

    previous() {

        const song = getPreviousFile()[0]
        var previousList = getPreviousFile()
        previousList.splice(0, 1)
        savePreviousFile(previousList)

        return song

    }

    setCurrent(song) {
        
       
        current = song.current
        console.log("CURRENT SONG : " + current.title)
  
    }

    addCurrentToPrevious(song) {
        if(song) {
            var previousList = getPreviousFile()
            previousList.unshift(song)
            savePreviousFile(previousList)
        } else if(current) {
            var previousList = getPreviousFile()
            //Check if the first song is the same as the current song
            previousList.unshift(current)
            savePreviousFile(previousList)
        }


       
 
    }

    haveSongs() {

        if(next.length == 0) {
            return false

        } else{
            return true
        }
        
    }

    havePreviousSongs() {

        var previousList = getPreviousFile()
        if(previousList.length == 0) {
            return false

        } else{
            return true
        }
        
    }



    getNextSong() {

        const song = next[0]
        return song
       
    }


    async add(song, interaction) {

        if(!song) {
            process.emit("MUSIC_UPDATE_STATE")
            return
        }
        
        dlog.log("Ajout d'un titre dans la liste de lecture : '" + song.title + "' de '" + song.author + "'")
        next.push(song)

        if(interaction) {

            const embed = await new EmbedBuilder()
            .setColor(0x15e6ed)
            .setTitle('**Ajout dans la liste de lecture **: ' + song.title)
            .setDescription('**Demandé par **' + interaction.member.user.username)
            .addFields({name: "Auteur", value: song.author},
                       {name: "URL", value: song.uri})
            .setThumbnail(song.artworkUrl)
            .setTimestamp();

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

        process.emit("MUSIC_UPDATE_STATE")
    }

    remove(song) {
        
        dlog.log("Supression d'un titre dans la liste de lecture : '" + song.title + "' de '" + song.author + "'")
        
        const index = next.indexOf(song)
        next.splice(index, 1)

    }

    removeByIndex(index) {

        dlog.log("Supression d'un titre dans la liste de lecture : '" + next[index].title + "' de '" + next[index].author + "'")
        
       
        next.splice(index, 1)

        process.emit("MUSIC_UPDATE_STATE")
    }

    moveUp(index) {

        let elementToMove = next[index]
        next.splice(index, 1)
        next.unshift(elementToMove);
        process.emit("MUSIC_UPDATE_STATE")
    }

    __previous_add(song) {
        if(song) {
            var previousList = getPreviousFile()
            previousList.unshift(song)
            savePreviousFile(previousList)
        }

    
    }

    __previous_remove(song) {
        if(song) {
            var previousList = getPreviousFile()
            previousList.splice(previousList.indexOf(song), 1)
            savePreviousFile(previousList)
        }
      
    }

    __next_add(song) {
        if(song) {
            next.unshift(song)
        }
      
    }

    async replaceList(data) {

        var newOrder = new Array()

        for(var numOrder of data) {
            parseInt(numOrder)
            
            newOrder.push(next[numOrder])
            
            
        }
        next = newOrder
        process.emit("MUSIC_UPDATE_STATE")

    }

    async playlistAdd(playlist, interaction, userId, quick ) {

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

        if(interaction) {

            var author = "Artiste inconnu !"

                if(typeof playlist.author != "undefined" ) {

                    author == playlist.author.name
                }


            const embed = await new EmbedBuilder()
            .setColor(0x15e6ed)
            .setTitle('**Lecture de la playlist : **' + playlist.title)
            .setDescription('**Demandé par **' + interaction.member.user.username)
            .addFields({name: "Auteur", value: author},
                      {name: "URL", value:playlist.url},
                      {name: "Nombre de videos", value:playlist.video_count + " vidéos"})
            .setThumbnail(playlist.thumbnail_url)
            .setTimestamp();

            interaction.reply({embeds: [embed]})
            player = client.manager.players.get(interaction.guild.id)

            userId = interaction.member.user.id


        }

            var numberExecuted = 0
            for(var song of playlist.videos) {
                if(song.uri) {
                    song.url = song.uri
                } 
                const song_finded = await client.manager.search(song.url)
                // Avoid if song not found
                if(!song_finded.tracks[0]) {
                    numberExecuted += 1 
                    continue
                }
                next.push(song_finded.tracks[0])
                numberExecuted++
                if(numberExecuted == playlist.videos.length) {
                    
                    process.emit("MUSIC_UPDATE_STATE")
                }
              
            }

            if(!player) { 

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

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


            if(!player.playing) {

                player.play(next[0])
                this.remove(next[0])
             
            } else {
                if(quick) {
                    player.play(next[0])
                    this.remove(next[0])
                }
            }

          

           

    } 

}


/**
 * 
 * @returns {Array} 
 */
function getPreviousFile() {
    return JSON.parse(fs.readFileSync(__glob.PREVIOUS_FILE, 'utf8'))
}


function savePreviousFile(db) {

    // Add a security to avoid a too big file
    if(db.length > 25) {
        db.splice(25, db.length - 25)
    }


    fs.writeFileSync(__glob.PREVIOUS_FILE, (JSON.stringify(db, null, 2)))

}