function generateRandomId() {
    return 'div-' + Math.random().toString(36).substr(2, 9);
}


function changeImg(end = true) {

    const imgElement = document.getElementById('pause-button');
    if (imgElement) {
        if (end) {
            imgElement.src = './soundFilled.png'; 
        } else {
            imgElement.src = './pause-circle-outlined.png';
        }
    
    }

}

function pausePlayerV2(url, volume = 0.8) {

    console.log("pausePlayerV2", url, volume)

    const randomId = generateRandomId();
    const newDiv = document.createElement('audio');
    newDiv.id = randomId;

    newDiv.src = url;
    newDiv.volume = volume
    // newDiv.muted = true

    changeImg(false)

    newDiv.play().then(() => {

        newDiv.addEventListener('ended', () => {
            
            _firstRun = true;

            console.log('Playback finished');

            changeImg(true)

            postParentMessage('finished')

      }, { once: true });

    }).catch(e => {

        console.error(e, e.message, url);

        changeImg(true)
    });

}


let currentData = {}

document.body.addEventListener('click', function(event) {

    pausePlayerV2(currentData.url, currentData.volume)

});

function postParentMessage(data) {
    window.parent.postMessage(data, "*");
}
  


window.onload = function(){
    window.addEventListener('message',function(e){

            currentData = e.data

            console.log('audio message', currentData)

            pausePlayerV2(currentData.url, currentData.volume)

    })
}
