function getID(id) {
    return document.getElementById(id);
}   

function getTimeCode(duration) {
    var max = ""
   

    const maxhours = Math.floor(duration / 3600000);

    var maxmin = Math.trunc(duration / 60000) - (Math.floor(duration / 60000 / 60) * 60);
    var maxsec = Math.floor(duration / 1000) - (Math.floor(duration / 1000 / 60) * 60);


    if (maxsec < 10) {
        maxsec = `0${maxsec}`;
    }


    if(maxhours != 0) {

        if (maxmin < 10) {
            maxmin = `0${maxmin}`;
        }

        
        max = maxhours + ":" + maxmin + ":" + maxsec
    } else {
        max =  maxmin + ":" + maxsec
    
    }
    return max
}

var xMousePos = 0;
var yMousePos = 0;


document.onmousemove = function(e)
{
  xMousePos = e.clientX + window.scrollX;
  yMousePos = e.clientY + window.scrollY;

}


class User {
    constructor(properties) {
        this.userImg = properties.picture
        this.userName = properties.name
        this.userId = properties.id
    
    }

    generateHTML() {
        return `<div class="ousercard_div">
                    <img id="ouser-img" class="ousercard_image" src="${this.userImg}"></img>
                    <div class="usercard_text">
                        <p id="ouser-name" class="ousercard_text_name">${this.userName}</p>
                        <p id="ouser-id" class="ousercard_text_id">${this.userId}</p>
                    </div>
                </div>`
    }

   
}

var ActualDroppableMenu = null


class DroppableMenu {
    options = new Array()
    id = null
    DMSpanInteger = null

    constructor() {
 
        this.id = Math.random().toString(36).substring(7)
        
    }

    add(action, string) {
      
        this.options.push("<div id='" + this.id + "_" + action + "' class='dm-element'>" + string + "</div>")
        
    }

    show() {
            console.log("DROPPABLE MENU - " + this.id)
            
            if(ActualDroppableMenu) {
                ActualDroppableMenu.hide()
            }


            ActualDroppableMenu = this
            
            if(xMousePos && yMousePos) {
             
                this.DMSpanInteger = document.createElement("span")
                this.DMSpanInteger.id = "dm-" + this.id
                this.DMSpanInteger.className = "dm-span"
          
                document.body.appendChild(this.DMSpanInteger);

                this.DMSpanInteger.innerHTML = this.options.join('')
                const menu = getID(`dm-${this.id}`)

                menu.style.position = "absolute"
                menu.style.left = (xMousePos - 100) + "px" 
                menu.style.top = (yMousePos - 40) + "px"
                
                menu.addEventListener("mouseleave", () => { 
                
                    this.hide()
                    
                })

                menu.addEventListener("click", () => { 
                    this.hide() 
                })
            }
         
    }

    get(action) {

        return getID(this.id + "_" + action)
    }

    hide() {
       
        const menu = getID(`dm-${this.id}`)
        if(menu) {
            menu.outerHTML = ""
            console.log("HIDED")
        }

    }
}


class ModalComponent {
    /**
     * @type {HTMLElement}
     */
    Element;
    constructor(properties) {
        this.title = properties.title
        this.content = properties.content
        this.closable = true
        if(properties.closable != null) {
            this.closable = properties.closable
        } 
        if(properties.width) {
            this.width = properties.width
        } else {
            this.width = "50%"
        }   
    }

    show() {
        var closableDiv = "<span id='modal-close'>&times;</span>"
        if(this.closable == false) {
            closableDiv = ""
        }
        
        this.Element = document.createElement("div")
        this.Element.className = "modal"
        this.Element.id = this.id
        this.Element.innerHTML = `<div id='modal-content' class="modal-content">
                                    <div class="modal-header">
                                        <h2>${this.title}</h2>
                                        ${closableDiv}
                                    </div>
                                    <div class="modal-body">
                                        ${this.content}
                                    </div>
                                </div>`
        document.body.appendChild(this.Element)
        this.Element.style.display = "flex"
        
        // Edit the width of modal content
        const modalContent = getID("modal-content")
        modalContent.style.width = this.width

        if(this.closable) {

            const close = getID("modal-close")
            close.addEventListener("click", () => { 
                this.hide()
            })

        }

    } 

    hide() {

        if(this.Element && this.Element.parentElement) {
            this.Element.outerHTML = ""
        }
  

    }

    setContent(content) {
        this.content = content

    }



}

class VideoComponent {
    constructor(data, playlist) {

        if(playlist) {
            this.onPlaylist = true
            this.title = data.title
            this.author = data.author.name
            this.thumbnail = data.thumbnail_url
            this.url = data.url
            this.duration = data.milis_length   
            this.identifier = data.id
            this.type = data.type
            this.self = data
        } else {
            this.onPlaylist = false
            this.title = data.title
            this.author = data.author
            this.thumbnail = data.artworkUrl
            this.url = data.uri
            this.duration = data.duration   
            this.identifier = data.identifier
            this.type = data.type
            this.self = data
        }
    }
    
    generateHTML(playlist, onYoutube) {

        var actions = ``
        var timecode = null

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

        if(playlist) {
            actions = `
            <span id="${this.identifier}_search_add" class="search-circle"><i class="fa fa-add"></i></span>
            <span id="${this.identifier}_search_play" class="search-circle"><i class="fa fa-play"></i></span>
            ${!onYoutube ? `<span id="${this.identifier}_search_padd" class="search-circle"><i class="fa fa-trash"></i></span>` : ""}

            `
        } else {
            actions = `<span id="${this.identifier}_search_add" class="search-circle"><i class="fa fa-add"></i></span>
            <span id="${this.identifier}_search_play" class="search-circle"><i class="fa fa-play"></i></span>
            <span id="${this.identifier}_search_padd" class="search-circle"><i class="fa fa-save"></i></span>`

        }


        return ` <div class="search-list-item" id="${this.identifier}_search">
            <div id="${this.identifier}_search_image"  class="search-list-item-image">
                <span class="search-action">
                    ${actions}
                </span>
                <p class='search-time-code'>${timecode}</p>        
            </div>
            <div class="search-list-item-text">
                <p class="search-list-item-text-title">${this.title}</p>
                <p class="search-list-item-text-channel">${this.author}</p>
            </div>  
        </div>`
    }

    loadScript(fromPlaylist, onYoutube) {
        const image = getID(`${this.identifier}_search_image`)
        image.style.backgroundImage = `url(${this.thumbnail})`

        const play = getID(`${this.identifier}_search_play`)
        const add = getID(`${this.identifier}_search_add`)
        const padd = getID(`${this.identifier}_search_padd`)
        
        add.addEventListener("click", () => {   
            const action = this.onPlaylist ? "FP_ADD_SONG" : "ADD_SONG";
            post(action, this.onPlaylist ? this.url : this.self);
        });

        play.addEventListener("click", () => {
            const action = this.onPlaylist ? "FP_ADD_SONG_NOW" : "ADD_SONG_NOW";
            post(action, this.onPlaylist ? this.url : this.self);
        });

        if(!fromPlaylist) {
            padd.addEventListener("click", () => {
                saveToPlaylist(this.url)
            })
        } else {
            if(onYoutube) {
              
                padd.addEventListener("click", () => {
                    post("DELETE_SONG_TO_PLAYLIST", {"id": playlistId, "identifier": this.identifier})
                })
            }
           
        }

       

        

    
    }



    loadPlaylist() {
        const image = getID(`${this.identifier}_search_image`)
        image.style.backgroundImage = `url(${this.thumbnail})`


    }
}

var playlistId = null


const viewEdit = getID("view-edit")

function loadView(content) {
    viewEdit.innerHTML = content
}

const tileList = new Array()

function setTileActive(tile) {
    playlistId = null

    // add only the 'invert' class to the selected tile by the id

    tileList.forEach((element) => {
        if(element) {
            element.classList.remove("invert")
        }
    })

    if(tile) {
        getID(tile).classList.add("invert")
    }
}


function loading(returnable) {

    if(returnable) {
        return `<p class='loading'><i class="fa-solid fa-rotate fa-spin"></i> Chargement en cours ... </p>`
    
    } else {
        loadView(`
        <p class='loading'><i class="fa-solid fa-rotate fa-spin"></i> Chargement en cours ... </p>
        `)
    }
  
}

function saveToPlaylist(url) {
    get("PLAYLIST").then((res) => { 
                    
        var allPlaylistOptions = new Array()
        for(var playlist in res) {
            var indicator = "[Privée] "

            if(res[playlist].source == "shared") {
                indicator = "[Partagée] "
            } 
            
            if(res[playlist].source != "youtube") {
                allPlaylistOptions.push(`<option value="${playlist}">${indicator}${res[playlist].title}</option>`)
            }

           
  
        }

        if(allPlaylistOptions.length == 0) {
            //Make a modal named "Error" with close button and a message
            const modalError = new ModalComponent({"title": "<i style='transform: scale(0.8);' class='fa fa-warning'></i> Erreur", width: "20%"})

            modalError.setContent(`<div class="modal-form">
            <p>Vous n'avez aucune playlist pour ajouter cette musique</p>
            </div>`)
            modalError.show()
            

            

        } else {

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

            modal.setContent(`
            <div class="modal-form">
            <select id="playlist-id">
            ${allPlaylistOptions.join("")}
            </select>
            <button id="playlist-add-confirm">Envoyer</button>
            </div>
            `)
            modal.show()

            const confirm = getID("playlist-add-confirm")
            const playlistId = getID("playlist-id")

            confirm.addEventListener("click", () => {
                post("ADD_SONG_TO_PLAYLIST", {"id": playlistId.value, "url": url})
                modal.hide()
            })

        }
    })
}