const listDiv = document.getElementById("list-div");
const listNext = document.getElementById("list-next"); 
const listPrevious = document.getElementById("list-previous");
const listClear = document.getElementById("list-clear");

var selectedQueue = "next"

var previousQueue = new Array()
var nextQueue = new Array()

listClear.addEventListener("click", function() {
    post("DELETE_ALL_QUEUE")
})

listNext.addEventListener("click", function() {
    listClear.style.display = "flex"
    listPrevious.classList.remove("selected") 
    listNext.classList.add("selected")
    selectedQueue = "next"
    showQueue(nextQueue, "next")
})

listPrevious.addEventListener("click", function() { 

    listClear.style.display = "none"
    listNext.classList.remove("selected")
    listPrevious.classList.add("selected")
    selectedQueue = "previous"
    showQueue(previousQueue, "previous")
})



function loadQueue(queue, type) {
    if(type == "next") {
        nextQueue = queue
    } else if(type == "previous") {
        previousQueue = queue
    }
    
}

function showQueue(queue, type) {
   
    listDiv.innerHTML = ""
    if(!queue) {
        listDiv.innerHTML = `
     
        <div class='no-song'>
            <span class="no-song-icon"><i class="fa-solid fa-link-slash"></i></span>
            <p>Subsonics est déconnecté</p>
        </div>`
        if(type == "previous") {
           listDiv.innerHTML =  `
           <div class='no-song'>
           <span class="no-song-icon"><i class="fa-solid fa-volume-xmark"></i></span>
           <p>Aucune musique jouée</p>
            </div>
           
           `
        }

    } else if(queue.length > 0) {
        console.log(queue)        
        var videoList = new Array()

        for(var song of queue) {
            if(type == "next") {
                song.type = "next"
            } else {
                song.type = "previous"  
            }
            song.numList = queue.indexOf(song)
            var video = new VideoQueue(song)
            listDiv.innerHTML += video.generateHTML()
            videoList.push(video)
        }

        for(var video of videoList) {
      
           video.loadScript()
        }

        const container = listDiv;
        const draggableItems = document.querySelectorAll('.draggable');

        let draggingElement = null;

        draggableItems.forEach(item => {
            item.addEventListener('dragstart', (e) => {
            e.dataTransfer.setData('text/plain', item.innerHTML);
            draggingElement = item;
            });

            item.addEventListener('dragend', () => {
            draggingElement = null;
            setTimeout(() => {
                item.style.display = 'flex'; // Restaure l'affichage de l'élément
            }, 0);
            updateOrder();
            });
        });

        container.addEventListener('dragover', (e) => {
            e.preventDefault();
            const afterElement = getDragAfterElement(container, e.clientY);
            if (draggingElement !== null) {
            if (afterElement == null) {
                container.appendChild(draggingElement);
            } else {
                const rect = afterElement.getBoundingClientRect();
                if (e.clientY < rect.top + rect.height / 2) {
                container.insertBefore(draggingElement, afterElement);
                } else {
                container.insertBefore(draggingElement, afterElement.nextElementSibling);
                }
            }
            }
        });
        
    } else {
        if(type == "next") {
            listDiv.innerHTML =  `
            <div class='no-song'>
            <span class="no-song-icon"><i class="fa-solid fa-volume-xmark"></i></span>
            <p>Aucune musique n'est en attente</p>
             </div>
            
            `
        } else if(type == "previous") {
            listDiv.innerHTML =  `
           <div class='no-song'>
           <span class="no-song-icon"><i class="fa-solid fa-volume-xmark"></i></span>
           <p>Aucune musique jouée</p>
            </div>
           
           `
        }
    }
}

function actualiseQueue() {
    if(selectedQueue == "next") {
        showQueue(nextQueue, "next")
    } else if(selectedQueue == "previous") {
        showQueue(previousQueue, "previous")
    }
}


class VideoQueue {
    constructor(data) {
        console.log(data)
        this.title = data.title
        this.author = data.author
        this.thumbnail = data.artworkUrl
        this.url = data.url
        this.duration = data.duration   
        this.identifier = data.numList + "_" + data.identifier
        this.type = data.type
        this.numList = data.numList
    }
    
    generateHTML() {
        var dragOn = ""
        var idOn = ""
        if(this.type == "next") {  
            dragOn = "draggable"
            idOn = `${this.numList}_queue_song`
        }

        var timecode = null

        // Check if live 

        if(this.duration == 9223372036854776000) {
   
            timecode = "<i class='red fa-solid fa-circle'></i> LIVE"
            
        } else {
            timecode = getTimeCode(this.duration)
        }

       return `
       <div id='${idOn}' class="list-video ${dragOn}">
            <div class="list-video-div">
                <div class="list-video_image"><img class="showPicture" src="${this.thumbnail}"><p class='list-time-code'>${timecode}</p></div>
                <div class="list-video_title">
                    <span class="list-video_title_title"><p>${this.title}</p></span>
                    <span class="list-video_title_channel"><p>${this.author}</p></span>
                </div>
            </div>
            <span id='${this.identifier}' class="list-video-elipsis"><i class="fa-solid fa-ellipsis-vertical"></i></span>
        </div>`
    }

    loadScript() {
        const identifier = getID(this.identifier)
        const menu = new DroppableMenu()

        

            menu.add("play", "<i class='fa fa-play'></i> Lire")    
            if(this.type == "next") {
                menu.add("up", "<i class='fa fa-list-ol'></i> <p>Placer au dessus</p>")
                menu.add("delete", "<i class='fa fa-trash'></i> <p>Supprimer</p>")
            } else {
                menu.add("add", "<i class='fa fa-list-ol'></i> <p>Ajouter à la file d'attente</p>")
            }

            // Add to a playlist

            menu.add("playlist", "<i class='fa fa-plus'></i> <p>Ajouter à une playlist</p>")
        
        identifier.addEventListener("click", (event) => {
            if(event.ctrlKey || event.metaKey) {
                post("DELETE_QUEUE", this.numList, this.title)
            } else {
                menu.show()

                const play = getID(`${menu.id}_play`)
                const playlist = getID(`${menu.id}_playlist`)

                playlist.addEventListener("click", () => {
                    saveToPlaylist(this.url)
                })
    
                play.addEventListener("click", () => {
                    post("PLAY_QUEUE", [this.numList, this.type])
                    
                })
    
                if(this.type == "next") {
    
                    const up = getID(`${menu.id}_up`)
                    const deleteEl = getID(`${menu.id}_delete`)
    
                    up.addEventListener("click", () => {
                        post("MOVE_QUEUE", this.numList)
                    })
    
                    deleteEl.addEventListener("click", () => {
                        post("DELETE_QUEUE", this.numList, this.title)
                    })
    
                } else {
                    const add = getID(`${menu.id}_add`)
    
                    add.addEventListener("click", () => {
                        post("CHANGE_QUEUE", this.numList)
                    })
                }

            }
        })



    }
}


function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')];
    return draggableElements.reduce((closest, child) => {
    const box = child.getBoundingClientRect();
    const offset = y - box.top - box.height / 2;
    if (offset < 0 && offset > closest.offset) {
        return { offset: offset, element: child };
    } else {
        return closest;
    }
    }, { offset: Number.NEGATIVE_INFINITY, element: null }).element;
}

function updateOrder() {
    const draggableItems = document.querySelectorAll('.draggable');
    const order = [];
    draggableItems.forEach(item => {
        order.push(item.id.replace("_queue_song", ""));
    });
    console.log('Ordre des divs:', order);
    post("MOVE_QUEUE_BY_ENTIRE", order)
}