const DIGITAL_SIGNAGE_BASE_URL = DigitalSignage4_getScriptDirectoryUrl().replace("Kernel/Views/js/", "");

DigitalSignage4_importScript("CronUpdateVideo");

function DigitalSignage4_getScriptDirectoryUrl() {
    let scripts = document.getElementsByTagName('script');
    let myScript = scripts[scripts.length - 1];
    let myScriptFullUrl = myScript.src;
    let myScriptFullUrlSplit = myScriptFullUrl.split('/');
    myScriptFullUrlSplit.pop();
    return myScriptFullUrlSplit.join('/') + "/";
}

function DigitalSignage4_importScript( scriptName ){
    let imported = document.createElement('script');
    imported.src = DigitalSignage4_getScriptDirectoryUrl() + scriptName + '.js';
    document.head.appendChild(imported);
}

var video_list = [];
var video_index = [];
var video_player = [];

function DigitalSignage4_onload()
{
    //Chercher dans le dom les balises video avec un paramètre playlist
    var balises = document.querySelectorAll('[playlist]');
    //Pour chaque identifiant de playlist, récupérer en ajax les vidéos, et les stocker dans video_list[identifiant de playlist]
    balises.forEach(e => 
    {
        var id_playlist = e.getAttribute('playlist');
        video_index[id_playlist] = 0;
        video_player[id_playlist] = e;
        //let url = DIGITAL_SIGNAGE_BASE_URL + "Classes/DigitalSignage4_FrontShortcodeVideoDisplayerAjaxHandler.php?idPlaylist=" + id_playlist;
        let url = ajax_url + "?action=FrontShortcodeVideoDisplayerAjaxHandler&nonce=" + ajax_nonce + "&idPlaylist=" + id_playlist;
        let xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.onload = function () {
            if (this.responseText) {
                returnJSON = JSON.parse(this.responseText);
                video_list[id_playlist] = JSON.parse(returnJSON.data.message);
                video_player[id_playlist].setAttribute("src", video_list[id_playlist][video_index[id_playlist]]);
                video_player[id_playlist].load();
                video_player[id_playlist].play();
            } else {

            }
        };
        xhr.send();
    });
    //Pour chaque identifiant de playlist, initialiser video_index[identifiant de playlist]
    //Pour chaque identifiant de playlist, initialiser video_player[identifiant de playlist]
    
}
DigitalSignage4_onload();

function DigitalSignage4_onVideoEnded( idPlaylist ){
    if(video_index[idPlaylist] < video_list[idPlaylist].length - 1){
        video_index[idPlaylist]++;
    }
    else{
        video_index[idPlaylist] = 0;
    }

    video_player[idPlaylist].setAttribute("src", video_list[idPlaylist][video_index[idPlaylist]]);

    video_player[idPlaylist].load();
    video_player[idPlaylist].play();
}