function loadButtons() {
    fetch('/static/content/buttons/non_link_buttons.txt').then(response => {
        return response.text();
    }).then(data => {
        container = document.getElementById('button-collection');
        for (let line of data.split('\n')) {
            if (line == "") {
                continue;
            }
            let img = document.createElement('img');
            img.src = line;
            container.appendChild(img);
        }
    });
}


function getAlbumArt(songName, artistName) {
    fetch("/music/metadata?recording_name=" + encodeURIComponent(songName) + "&artist_name=" + encodeURIComponent(artistName)).then(response => response.json()).then(data => {
        if (Object.keys(data).length > 0) {
            document.getElementById('listenbrainz').style.backgroundImage = "url(https://coverartarchive.org/release/" + data.release_mbid + "/front)";
        } else {
            console.log("No album art found for the given song and artist");
            document.getElementById('listenbrainz').style.backgroundImage = "url(https://placehold.co/512x512/transparent/777?text=[Insert%20art%20here])";
        }
    });    
}

function getMusic() {
    fetch("https://api.listenbrainz.org/1/user/acetheking987/playing-now").then(response => response.json()).then(data => {
        if (data.payload.count != 0) {
            let song_data =  data.payload.listens[0].track_metadata;
            getAlbumArt(song_data.track_name, song_data.artist_name);
            document.getElementById('listenbrainz-title').innerHTML = song_data.track_name;
            document.getElementById('listenbrainz-artist').innerHTML = song_data.artist_name;
            document.getElementById('listenbrainz-link').href = "https://listenbrainz.org/user/acetheking987/";
            document.getElementById('listenbrainz-live').style.backgroundColor = "red";
            document.getElementById('listenbrainz-live').innerHTML = "Live";
        } else {
            fetch("https://api.listenbrainz.org/1/user/acetheking987/listens?count=1").then(response => response.json()).then(data => {
                if (data.payload.count != 0) {
                    let song_data =  data.payload.listens[0].track_metadata;
                    getAlbumArt(song_data.track_name, song_data.artist_name);
                    document.getElementById('listenbrainz-title').innerHTML = song_data.track_name;
                    document.getElementById('listenbrainz-artist').innerHTML = song_data.artist_name;
                    document.getElementById('listenbrainz-link').href = "https://listenbrainz.org/user/acetheking987/";
                    document.getElementById('listenbrainz-live').style.backgroundColor = "grey";
                    document.getElementById('listenbrainz-live').innerHTML = "Not Live :<";
                }
            });
        }
    });
}

loadButtons();
getMusic();
setInterval(getMusic, 15000);