const play = getID("play")
const forward = getID("forward")
const backward = getID("backward")
const loop = getID("loop")
const shuffle = getID("shuffle")

const durationBar = getID("duration")

const video_img = getID("video_img")
const video_title = getID("video_title")
const video_artist = getID("video_artist")

const time_act = getID("time_act")
const time_total = getID("time_total")

const volume = getID("volume")
const volIcon = getID("volIcon")
const volTxt = getID("volTxt")

const lyrics = getID("lyrics")

const disconnect = getID("disconnect")
const moveout = getID("moveout")

var durationAct = 0
var durationTotal = 0

// 4 States : PLAYING, PAUSED, CONNECTED, DISCONNECTED, LIVE

var interval = null

var currentTitle = null

var playerState = "DISCONNECTED"

AlwaysRequest("MUSIC_STATE", async (data) => {
    durationAct = 0
    durationTotal = 0
    playerState = "DISCONNECTED"
    currentTitle = null
    stopInterval()

    console.log(data)

    if(data.isOnline) {

        playerState = "CONNECTED"

        forward.classList.remove("disabled")
        backward.classList.remove("disabled")
        loop.classList.remove("disabled")
        shuffle.classList.remove("disabled")
        disconnect.classList.remove("invisible")
        moveout.classList.remove("invisible")
        volume.classList.remove("invisible")
        volTxt.classList.remove("invisible")
        volIcon.classList.remove("invisible")
        lyrics.classList.remove("invisible")
       
      
    } else {
        play.classList.add("disabled")
        forward.classList.add("disabled")
        backward.classList.add("disabled")
        loop.classList.add("disabled")
        shuffle.classList.add("disabled")
        moveout.classList.add("invisible")
        disconnect.classList.add("invisible")
        volume.classList.add("invisible")
        volIcon.classList.add("invisible")
        volTxt.classList.add("invisible")
        time_act.innerHTML = "&nbsp"
        time_total.innerHTML = "&nbsp"
        durationBar.classList.add("invisible")
        lyrics.classList.add("invisible")
    
    }

    if(data.shuffle == true) {
        shuffle.classList.add("point")

    } else {

        shuffle.classList.remove("point")
    }

    if(data.loop == true) {
        loop.classList.add("point")

    } else {

        loop.classList.remove("point")
    }

    
    if(data.current) {
        var thumbnail = data.current.artworkUrl

        if(thumbnail) {
            video_img.innerHTML = '<img class="showPicture" src="' + thumbnail + '">'
        }

        currentTitle = data.current.title
        video_title.innerHTML = "<p>" + data.current.title  + "</p>"
        video_artist.innerHTML = "<p>" + data.current.author + "</p>"

        // Get the width of the title and check if it's above 400px (the max width of the title)
        var titleWidth = video_title.querySelector("p").offsetWidth
        if(titleWidth > 400) {
            video_title.innerHTML = "<p>" + data.current.title  + " -</p>" + "<p>" + data.current.title  + " -</p> "
            video_title.classList.add("scroll")
        } else {
            video_title.classList.remove("scroll")
        }

        video_img.classList.remove("invisible")
        video_title.classList.remove("invisible")
        video_artist.classList.remove("invisible")
       

        
        play.classList.remove("disabled")
        setTime()
        
      
    } else {
       
        video_img.classList.add("invisible")
        video_title.classList.add("invisible")
        video_artist.classList.add("invisible")
        

        play.classList.add("disabled")
        currentTitle = null
    }

    if(data.queue) {
        loadQueue(data.queue, "next")
        actualiseQueue()
    } else {
        loadQueue(null, "next")
        actualiseQueue()
    }

    if(data.previous) {
        loadQueue(data.previous, "previous")
        actualiseQueue()
    } else {
        loadQueue(null, "previous")
        actualiseQueue()
    }


    if(data.volume) {
        volume.step = 1
        volume.max = 150
        volume.min = 1
        volume.value = Math.trunc(data.volume / 10)
        volTxt.innerHTML = Math.trunc(data.volume / 10) + "%"

        var volNum = Math.trunc(data.volume / 10)

        if(volNum == 1) {
            volIcon.innerHTML = '<i class="red fa-solid fa-volume-mute"></i>'
        } else if(volNum < 99) {
            volIcon.innerHTML = '<i class="fa-solid fa-volume-down"></i>'
        } else {
            volIcon.innerHTML = '<i class="fa-solid fa-volume-up"></i>'
        }

      

    } 

    
    
    if(data.playing == 1) {
        play.innerHTML = '<i class="fas fa-pause icon"></i>'
        playerState = "PLAYING"
        startInterval()
    } else {
        
        play.innerHTML = '<i class="fas fa-play icon"></i>'
        playerState = "PAUSED"
       
    }

    if(data.durationAll) {
     
        if(data.durationAll == 9223372036854776000) {
            durationBar.classList.add("invisible")
            time_act.innerHTML = ""
            time_total.innerHTML = "<i class='red fa-solid fa-circle'></i> LIVE"
            playerState = "LIVE"
        }  else {
           
            durationTotal = data.durationAll
            durationAct = data.durationNow
            setTime()
            durationBar.disabled = false
            durationBar.max = durationTotal
            durationBar.value = durationAct
            durationBar.classList.remove("invisible")
            setTime()
        }
    
       
    } else {

        durationBar.classList.add("invisible")
        durationBar.disabled = true
        time_act.innerHTML = "&nbsp"
        time_total.innerHTML = "&nbsp"

    }



    
})


loop.addEventListener("click", () => {

    get("LOOP")
})

shuffle.addEventListener("click", () => {

    get("SHUFFLE")
})


disconnect.addEventListener("click", () => {

    get("DISCONNECT")
})


durationBar.addEventListener("click", (event) => {
    stopInterval()
    post("SEEK", durationBar.value)
    startInterval()
})
 
durationBar.addEventListener("input", (event) => {
    stopInterval()
    time_act.innerHTML = getTimeCode(durationBar.value)
})

volume.addEventListener("click", () => {


    post("VOLUME", volume.value)
})

volume.addEventListener("dblclick", () => {
    
    post("VOLUME", 80)
})

play.addEventListener('click', () => {

    get("PAUSE")
})

forward.addEventListener('click', () => {

    get("FORWARD")
})

backward.addEventListener('click', () => {  
    
    get("BACKWARD")
})


moveout.addEventListener('click', () => {
    get("MOVEOUT")
})

lyrics.addEventListener('click', (e) => {
   
    currentTitle = currentTitle.replace(/\(.*?\)/g, "").replace(/\[.*?\]/g, "").trim()

    if(e.ctrlKey) {
        const modal = new ModalComponent({"title": "Rechercher des paroles" , "width": "25%", "closable": true})

        modal.setContent(`
        <div class='lyrics-finder'>
        <input id="lyrics_search" type="text" placeholder="Rechercher des paroles">
        <button id="lyrics_search_btn">Rechercher</button>
        </div>
        `)

        modal.show()

        const lyricsSearch = getID("lyrics_search")
        const lyricsSearchBtn = getID("lyrics_search_btn")

        lyricsSearchBtn.addEventListener('click', () => {
            showLyrics(lyricsSearch.value)
            modal.hide()
        })

    } else {

        if(currentTitle) {
            showLyrics(0)

        } else {
            const modal = new ModalComponent({"title": "Paroles" , "width": "20%", "closable": true})
            modal.setContent(`

            <p class="lyrics">Lancez une musique pour rechercher les paroles ou faites Ctrl + Click !</p>
            `)

            modal.show()
        }
    }


})

function showLyrics(title) {
  
    post("LYRICS", title).then((res) => {
        console.log(res)
        if(res.lyrics) {

           
            setTileActive(null)

            loadView(`
            <h1>Paroles de ""</h1>
            <div class="lyrics-container">
                <div class="lyrics-list">
          
                </div>  
            </div>
            `)


           
        }
    })

}


volIcon.addEventListener('click', () => {

    if(volume.value > 1) {
        post("VOLUME", 1)
    } else {
        post("VOLUME", 80)
    }
})

document.body.onkeyup = function(e) {

    if ((e.key == " " ||
        e.code == "Space" ||      
        e.keyCode == 32) &&
        e.srcElement.localName != "input" && e.srcElement.localName != "textarea"   
    ) {
        play.click()
    }
  }


// Function with setTime

function setTime() {

durationBar.max = durationTotal
durationAct += 1000 
durationBar.value = durationAct
  
  time_act.innerHTML = getTimeCode(durationAct)
  time_total.innerHTML = getTimeCode(durationTotal)
  
}

function startInterval() {
    interval = setInterval(() => {
  
  
        if(playerState == "PLAYING" && currentTitle) {
            setTime()
    
        } 
    
    }, 1000)
  
  }
  
  function stopInterval() {
    clearInterval(interval);
  }