const playlistList = getID("playlist-list")
const playlistAdd = getID("playlist-add")
var loadingPlaylist = false 


playlistAdd.addEventListener("click", () => {
    const win = new ModalComponent({
        "title": "<i style='transform: scale(0.8);' class='fa fa-music'></i> Ajouter une playlist",
        "width": "20%",
    })

    win.setContent(`
    <div class="modal-form">
        <input id="playlist-name" type="text" placeholder="Nom de la playlist">
        <select id="playlist-source">
            <option value="normal">Privée</option>
            <option value="shared">Partagée</option>
            <option value="youtube">Youtube</option>
        </select>
        <input id="playlist-url" type="text" placeholder="URL de la playlist">
        <span id='playlist-add-info'></span>
        <button id="playlist-add-confirm">Ajouter</button>
        </div>
    `)

    win.show()

    const confirm = getID("playlist-add-confirm")
    const name = getID("playlist-name")
    const source = getID("playlist-source")
    const url = getID("playlist-url")

    url.style.display = "none"

    confirm.addEventListener("click", () => {
        if(source.value == "youtube" && url.value.length == 0) {
            getID("playlist-add-info").innerHTML = "<i class='fa fa-warning'></i> L'URL de la playlist ne peut pas être vide"
            return
        }
        if(name.value.length > 0) {
            var data = {
                "name": name.value,
                "source": source.value,
                "url": url.value
            }
            post("CREATE_PLAYLIST", data).then((data) => {
                if(data.status == "error") {
                    getID("playlist-add-info").innerHTML = "<i class='fa fa-warning'></i>" + data.message
                } else {
                    win.hide()
                    loadPlaylistList()
                }
            })
        } else {
            getID("playlist-add-info").innerHTML = "<i class='fa fa-warning'></i> Le nom de la playlist ne peut pas être vide"
        }
    })

    source.addEventListener("change", () => {
        if(source.value == "youtube") {
            url.style.display = "block"
        } else {
            url.style.display = "none"
        }
    })
})

loadPlaylistList()

AlwaysRequest("PLAYLIST_REFRESH", () => {

    loadPlaylistList()
   

})

function loadPlaylistList() {
    get("PLAYLIST").then((data) => {

        var playlists = new Array()
        playlistList.innerHTML = ""

        for(var playlist in data) {

            const playlistTile = new PlaylistComponent(playlist, data[playlist])
            playlists.push(playlistTile)
            playlistList.innerHTML += playlistTile.generateHTML()

            if(playlistId == playlist) {
                loadPlaylist(playlistId, data[playlist])
            
            }
        }

        // Show a message if the playlist is empty

        if(playlists.length == 0) {
            playlistList.innerHTML = `<div class='no-song'>
            <span class="no-song-icon"><i class="fa-solid fa-circle-xmark"></i></span>
            <p>Aucune playlist</p>
            </div>`
        }


        for(var playlist of playlists) {
            playlist.loadScript()
        }

        


    })
}

class PlaylistComponent {
    constructor(id, data) {
       this.title = data.title
       this.id = id
       this.source = data.source
       this.content = data.content
       this.self = data
    }

    generateHTML() {

        var logo = "fa fa-music"
        if(this.source == "shared") {
            logo = "fas fa-share-alt"
        } else if(this.source == "youtube") {
            logo = "fab fa-youtube"
        }

        return `
        <div id='${this.id}' class="playlist-item">
            <div id='${this.id}_tile' class="playlist-item-tile">
                <i class="${logo}"></i>
            </div>
            <p>${this.title}</p>
        </div>`
    }

    loadScript() {
        const playlist = getID(this.id)
        const tile = getID(`${this.id}_tile`)

        tileList.push(tile)

        playlist.addEventListener("click", () => {
          
            loadPlaylist(this.id, this.self)
        })

    }

}


function loadPlaylist(id, properties) {
    if(loadingPlaylist) {
       return
    }
    if(!playlistId || playlistId != id) {
        loading()
    }
    setTileActive(id + "_tile")
    playlistId = id


    if(properties.source == "youtube") {
        loadingPlaylist = true
        post("SEARCH", properties.content).then((res) => {
            if(id == playlistId) {
                loadingPlaylist = false
                loadYoutubePlaylist(res, id, properties)
            }
      
        }) 
    } else {

        loadingPlaylist = false
        loadNormalPlaylist(id, properties)
        
    }
}

function loadNormalPlaylist(id, properties) {
    loadView(`
          
            <div style='padding-bottom: 15px;' class='search-playlist'>
            <div class='search-playlist-info'>
                <div class='playlist-item-tile'>
                    ${properties.source == "shared" ? "<i class='fas fa-share-nodes'></i>" : "<i class='fa fa-music'></i>"}
                </div>
                <div class='search-playlist-div'>
        
                    <p class='search-playlist-title'>${properties.title} <span id='pp-rename'><i class='search-playlist-rename fa fa-pen'></i></span></p>
                    <div>
                    <p class='search-playlist-desc'>${properties.content.length} titres </p>
                    </div>
                </div>
            </div>
            <div class='search-playlist-actions'>
                <span id='pp-add' class='wh'><i class='fa fa-add'></i></span>
                <span id='pp-play' class='wh'><i class='fa fa-play'></i></span>
                <span id='pp-send' class='wh'><i class='fa fa-paper-plane'></i></span>
                <span id='pp-delete' class='wh'><i class='fa fa-trash'></i></span>
            </div>
           </div>
           <div class="search-container">
              <div class="search-list" id="playlist-video-list">
              </div>
            </div>
          
            
            `)


            loadActions(null, id, properties)

            const playlistList = getID("playlist-video-list")

            var songList = new Array()

            playlistList.style.display = "grid" 

            for(var video of properties.content) {
                console.log(video)
                const videoTile = new VideoComponent(video, false)
                songList.push(videoTile)
                playlistList.innerHTML += videoTile.generateHTML(true, false)
            }

            

            // IF THE PLAYLIST IS EMPTY

            if(songList.length == 0) {
                playlistList.style.display = "flex" 
                playlistList.innerHTML = `<div class='search-no-song'>
                
                <span class="no-song-icon"><i class="fa-solid fa-circle-xmark"></i></span>
                <p>Aucun titre dans cette playlist</p>
                
                </div>`
            }

            for(var song of songList) {
                song.loadScript(true, true)
            }

}


function loadYoutubePlaylist(res, id, properties) {
    var author = ""
    console.log(res.results.author)

    if(res.results.author) {
         author = `
         <a target='_blank' style='text-decoration: none;' href='${res.results.author.url}'><div class='search-playlist-author'>
         <img  class='search-playlist-author-img' src='${res.results.author.avatar_url}'>
         <p class='search-playlist-author-name'>${res.results.author.name}</p>
         </div></a>
         `
    }
    loadView(`
          
            <div style='padding-bottom: 15px;' class='search-playlist'>
            <div class='search-playlist-info'>
                <div id='search-image-link' class='search-playlist-image'>
                    <img src='${res.results.thumbnail_url}' class='showPicture'>
                </div>
                <div class='search-playlist-div'>
        
                    <p id='playlist-title' class='search-playlist-title'>${res.results.title} <span id='pp-rename'><i class='search-playlist-rename fa fa-pen'></i></span></p>
                    <div>
                    <p class='search-playlist-desc'>${res.results.videos.length} titres - ${res.results.view_count} vues </p>
                    <p class='search-playlist-desc'> ${res.results.description}</p>
                    </div>
                    ${author}
                </div>
            </div>
            <div class='search-playlist-actions'>
                <span id='pp-add' class='wh'><i class='fa fa-add'></i></span>
                <span id='pp-play' class='wh'><i class='fa fa-play'></i></span>
                <span id='pp-send' class='wh'><i class='fa fa-paper-plane'></i></span>
                <span id='pp-delete' class='wh'><i class='fa fa-trash'></i></span>
            </div>
           </div>
           <div class="search-container">
              <div class="search-list" id="playlist-video-list">
              </div>
            </div>
          
            
            `)


            
            loadActions(res, id, properties)

            const playlistList = getID("playlist-video-list")
            const searchImageLink = getID("search-image-link")
            const playlistTitle = getID("playlist-title")
            
            searchImageLink.addEventListener("click", function(e) {
                if(e.ctrlKey) {
                    // Put in the clipboard properties.content
                    navigator.clipboard.writeText(properties.content)
                    
                    // Set the title green for 1 second

                    playlistTitle.style.color = "#32FF32"
                    setTimeout(() => {
                        playlistTitle.style.color = "white"
                    }, 1000)

                    

                } else {
                    window.open(properties.content, '_blank');
                }
            
            })


            var songList = new Array()

            console.log(res.results.videos)

            for(var video of res.results.videos) {
                const videoTile = new VideoComponent(video, true)
                songList.push(videoTile)
                playlistList.innerHTML += videoTile.generateHTML(true, true)
            }

            for(var song of songList) {
                song.loadScript(true)
            }
         
           
}

function loadActions(res, id, properties) {
    const ppAdd = getID("pp-add")
    const ppPlay = getID("pp-play")
    const ppSend = getID("pp-send")
    const ppDelete = getID("pp-delete")
    const ppRename = getID("pp-rename")

    ppRename.addEventListener("click", () => { 
   
        const win = new ModalComponent({
            "title": "<i style='transform: scale(0.8);' class='fa fa-music'></i> Renommer la playlist",
            "width": "20%",
        })

        win.setContent(`
        <div class="modal-form">
            <input id="playlist-rename-name" type="text" placeholder="Nom de la playlist" value="${properties.title}">
            <button id="playlist-rename-confirm">Renommer</button>
        </div>
        `)

        win.show()

        const confirm = getID("playlist-rename-confirm")
        const name = getID("playlist-rename-name")

        confirm.addEventListener("click", () => {
            if(name.value.length > 0) {
                post("RENAME_PLAYLIST", {id: id, name: name.value})
                win.hide()
            }
        })
    })
    

    ppAdd.addEventListener("click", () => {
        if(res) {
            post("FP_PLAY_PLAYLIST", res.results.url)
        } else {
            post("PLAY_PLAYLIST", id)
        }
  
    })

    ppPlay.addEventListener("click", () => {
        if(res) {
            post("FP_PLAY_PLAYLIST_NOW", res.results.url)
        } else {
            post("PLAY_PLAYLIST_NOW", id)
        }

    })

    ppDelete.addEventListener("click", () => {
        // Make a confirmation modal

        const win = new ModalComponent({
            "title": "<i style='transform: scale(0.8);' class='fa fa-trash'></i> Supprimer la playlist",
            "width": "15%",
        })
        

        win.setContent(`
        <div class="modal-form">

            <p style='text-align: center;'>Êtes-vous sûr de vouloir supprimer la playlist ?</p>
            <button id="playlist-delete-confirm">Supprimer</button>
        </div>
        `)

        win.show()

        const confirm = getID("playlist-delete-confirm")

        confirm.addEventListener("click", () => {
            post("DELETE_PLAYLIST", id)
            win.hide()
            loadSearch()
        })

      
    })

    ppSend.addEventListener("click", () => {
        get("USER_LIST").then((data) => {
            var userList = new Array()
            for(var userPS of data) {
                console.log(userPS)
                if(userPS.username != userId.innerHTML) {
                    userList.push(userPS)
                }

            }
            const win = new ModalComponent({
                "title": "<i style='transform: scale(0.8);' class='fa fa-music'></i> Envoyer la playlist",
                "width": "20%",
            })

            win.setContent(`
            <div class="modal-form">
                <select id="playlist-user">
                    ${userList.map((userPS) => `<option value="${userPS.id}">${userPS.username}</option>`)}
                </select>
                <button id="playlist-send-confirm">Envoyer</button>
            </div>
            `)

            win.show()

            const confirm = getID("playlist-send-confirm")
            const userS = getID("playlist-user")

            confirm.addEventListener("click", () => {
                post("SEND_PLAYLIST", {key: id, dest: userS.value})
                win.hide()
            })

        })
            
    })

}