{block name='content'}
    <div class="DigitalSignage4_card DigitalSignage4_wp_card playlist">
        {$form_nonce}
        <h2>{$t::getTraduction( "Ajout_playlist")}</h2>

        <br>

        <label for="name" style="display: flex;align-items: center;">
            {$t::getTraduction( "Nom_playlist")}
            <input type="text" id="name" onkeydown="isSave = false" value="{$playlist->get_title()}" style="width: 30ch;margin-left: 10px;">
        </label>

        <br><br>

        <div id="tuto_playlist">
            <p>{$t::getTraduction( "Tuto_ajout_video_playlist" , $t::getTraduction( "Vos_videos") , $t::getTraduction( "Videos_playlist") , $t::getTraduction( "Videos_playlist"))}</p>
        </div>

        <br>

        <div>
            <h2>{$t::getTraduction( "Videos_playlist")}</h2>

            <div id="videos_playlist" class="wrap_videos" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

            <br>

            <button class="btn DigitalSignage4_button btn-primary"
                    onclick="save_playlist()">{$t::getTraduction( "Save_playlist")}</button>

            <div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">

                        <div class="modal-body">
                            <p style="font-size: 1.3em">{$t::getTraduction( "Quitter_sans_save")} ?</p>
                        </div>

                        <div class="modal-footer">
                            <button style="font-size: 1.3em" type="button" class="btn btn-secondary"
                                    data-dismiss="modal">{$t::getTraduction( "Non")}
                            </button>

                            <button onclick="leaveAddPlaylist()" style="font-size: 1.3em" type="button"
                                    data-dismiss="modal" class="btn btn-primary">{$t::getTraduction( "Oui")}
                            </button>
                        </div>

                    </div>
                </div>
            </div>

            <script>

                let isSave = true;
                let URL_PLAYLIST = null;

                function saveUrlRedirection(url_input, element) {

                    URL_PLAYLIST = url_input;

                    if (isSave) {
                        element.removeAttribute('data-toggle');
                        leaveAddPlaylist();
                    }

                }

                function leaveAddPlaylist() {
                    document.location.href = URL_PLAYLIST;
                }


            </script>

        </div>

        <div id="adelete"></div>

        <div>
            <br><br>
            <h2>{$t::getTraduction( "Vos_videos")}</h2>


            <div style="display: flex;align-items: center;">
                <input type="text" id="search_input" placeholder="Recherche">

                <button onclick="search()" style="margin-left : 5px">
                    <span class="DigitalSignage4_material-icons"> search </span>
                </button>

            </div>

            <br><br>

        </div>

        <div id="videos_comtpe" class="wrap_videos">

            {$videoPlaylist}

        </div>

        <div id="newLoadnewVideo">
                        <span class="reloadIcon rotate_icon">
                          <i class="DigitalSignage4_material-icons">loop</i>
                      </span>
        </div>

        <script>

            function addPlayOnHover(video) {
                video.addEventListener("mouseenter", () => {
                    video.play();
                });

                video.addEventListener("mouseleave", () => {
                    video.pause();
                    video.currentTime = 0;
                });
            }

        </script>


    </div>
    <script>

        let playlist = document.getElementById('videos_playlist');
        let videosDomContainer = document.getElementById('videos_comtpe');

        let SRC = null;
        let DEST = null;

        let videos_playlist = {$playlist->get_videos()|json_encode};

        setVideoDefaut();

        var caras = "";

        function search() {

            caras = document.getElementById('search_input').value;
            offset = 0;
            canLoad = false;

            document.getElementById("newLoadnewVideo").style.display = "block";

            getVideosFromServer("&find=" + caras, true);

        }

        function setVideoDefaut() {

            let videoFound = false;

            videos_playlist.forEach((video_playlist) => {
                let video = document.getElementById('button_' + video_playlist);
                if (video) {
                    videoFound = true;
                    toggleVideoPlaylist(video);
                }
            });


            if (!videoFound) {
                addEmptyPlaylistMessageSpan();
            }

        }

        function addEmptyPlaylistMessageSpan() {
            let span = document.createElement("span");
            span.innerHTML = "{$t::getTraduction( "Playlist_vide")}";
            span.style.opacity = ".5";
            span.style.margin = "2em";
            span.id = "empty_playlis_message";
            document.getElementById("videos_playlist").appendChild(span);
        }

        function removeEmptyPlaylistMessageSpan() {
            let span = document.getElementById("empty_playlis_message");
            if (span)
                span.parentElement.removeChild(span);
        }

        function toggleVideoPlaylist(video) {

            if (video.innerHTML === "highlight_off") {
                video.innerHTML = "add_circle_outline";
            } else {
                video.innerHTML = "highlight_off";
            }

            video = video.parentElement.parentElement;

            video.classList.toggle("video_in_playlist");

            if (video.getAttribute('draggable')) {
                video.removeAttribute('draggable');
            } else {
                video.setAttribute('draggable', true);
            }

            isSave = false;

            if (video.parentElement.id === "videos_playlist") {
                videosDomContainer.insertBefore(video, videosDomContainer.firstChild);
            } else {
                playlist.appendChild(video);
            }

            if(document.getElementById("videos_playlist").childNodes.length !== 0){
                removeEmptyPlaylistMessageSpan()
            }else{
                addEmptyPlaylistMessageSpan();
            }

        }

        function allowDrop(ev) {
            ev.preventDefault();
            changePlace(ev);
        }

        function drag(ev) {
            SRC = ev;
            SRC.target.classList.add("in_drag");
        }

        /**
         * Change les videos de place
         * @param ev
         */
        function drop(ev) {
            isSave = false;
            ev.preventDefault();
            changePlace(ev);
            let temp = SRC.target;

            removeAll();
            temp.classList.add("fade_out_drag");

            setTimeout(() => {
                removeAll(false);
            }, 1000);

        }

        function removeAll(in_drag_remove = true) {

            if (in_drag_remove) {
                let videos = document.querySelectorAll(".in_drag");
                videos.forEach(function (userItem) {
                    userItem.classList.remove("in_drag");
                });
            }

            videos = document.querySelectorAll(".fade_out_drag");
            videos.forEach(function (userItem) {
                userItem.classList.remove("fade_out_drag");
            });

        }

        function changePlace(ev) {

            DEST = ev.target;

            if (DEST.tagName === "VIDEO") {

                let rect1 = DEST.parentElement.getBoundingClientRect();
                let rect2 = SRC.target.getBoundingClientRect();

                let SRC_2 = null;

                if (rect1.y === rect2.y) {

                    if (rect1.x > rect2.x) {

                        SRC_2 = SRC.target;
                        DEST = DEST.parentElement;
                        SRC.target = DEST;
                        DEST.replaceWith(SRC_2);
                        SRC_2.before(DEST);

                    } else {

                        SRC_2 = SRC.target;
                        DEST = DEST.parentElement;
                        SRC.target = DEST;
                        DEST.replaceWith(SRC_2);
                        SRC_2.after(DEST);
                    }

                } else {

                    if (rect1.y < rect2.y) {

                        SRC_2 = SRC.target;
                        DEST = DEST.parentElement;
                        SRC.target = DEST;
                        DEST.replaceWith(SRC_2);
                        SRC_2.after(DEST);

                    } else {

                        SRC_2 = SRC.target;
                        DEST = DEST.parentElement;
                        SRC.target = DEST;
                        DEST.replaceWith(SRC_2);
                        SRC_2.before(DEST);

                    }

                }
            }
        }

        function save_playlist() {


            let videos = getVideosIdsInPlaylist();
            let name = document.getElementById('name').value;

            if (name) {
                let form = new FormData();
                form.append("playlist_name", name);
                form.append("playlist_videos", JSON.stringify(videos));
                form.append("_wpnonce",ajax_nonce);

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '', true);

                xhr.onload = function () {


                    // do something to response
                    let response = stripScripts(this.responseText);

                    if (isJson(response)) {

                        let responseParsed = JSON.parse(response);

                        if (responseParsed[0] === "ok") {

                            let nextURL = window.location.href + '=' + responseParsed[1];

                            if(  window.location.href.slice(-1) === '='){
                                nextURL = window.location.href + responseParsed[1];
                            }


                            const nextTitle = '';
                            const nextState = '';
                            window.history.pushState(nextState, nextTitle, nextURL);
                            DigitalSignage4_showSuccessMessage("{$t::getTraduction( "Playlist_save")}");

                        } else {

                            DigitalSignage4_showErrorMessage("{$t::getTraduction( "Playlist_not_save")}");
                            DigitalSignage4_showErrorMessage(this.responseText);

                        }


                    } else if (response === "ok") {

                        DigitalSignage4_showSuccessMessage("{$t::getTraduction( "Playlist_save")}");
                        isSave = true;

                    } else {

                        DigitalSignage4_showErrorMessage(this.responseText);
                    }


                };

                xhr.send(form);

            } else {
                DigitalSignage4_showErrorMessage("{$t::getTraduction( "Playlist_nom_vide")}");
            }


        }

        function getVideosIdsInPlaylist() {
            //let videosInPlaylist = document.querySelectorAll('#videos_playlist > .add_playlist_video > video ');
			let videosInPlaylist = document.querySelectorAll('#videos_playlist > .add_playlist_video > video ');
            let videos = [];

            videosInPlaylist.forEach((videoInPlaylist) => {
                let url = videoInPlaylist.firstElementChild.src;
                let url_explode = url.split('/');
                let videoNumber = url_explode[url_explode.length - 2];
                videos.push(videoNumber);
            })
			
			let videosInPlaylist_youtube = document.querySelectorAll('#videos_playlist > .add_playlist_video > object ');
			videosInPlaylist_youtube.forEach((videoInPlaylist) => {
                let videoNumber = videoInPlaylist.name;
                videos.push(videoNumber);
				
            })
			
			
            return videos;
        }

        var offset = 0;
        var parLoad = 10;

        var canLoad = true; //permet de bloquer le double envois de la meme requete

        loadNewVideos();

        function getVideosFromServer(special = "", clear = false) {

            var xhr = new XMLHttpRequest();

            let url = window.location.href + '&loadVideos=true&start=' + offset + '&stop=' + (offset + parLoad) + "&nonce={$ajax_nonce}&playlistVue=update" + special;

			//console.log(url);
            xhr.open('GET', url, true);
            xhr.onload = function () {
				//alert(this.responseText);
                let response = stripScripts(this.responseText);
				//console.log("reponse stripScripts :"+response);
                canLoad = true;

                if (isJson(response)) {

                    let responseArray = JSON.parse(response);

                    if (responseArray[0] === "ok") {
					//if (responseArray["response"] === "ok") {
						//alert("reponse ok");
                        if (special && clear) {
                            document.getElementById('videos_comtpe').innerHTML = "";
                        }

                        if (responseArray[1]) {
						//if (responseArray["data"]) {
                            document.getElementById('videos_comtpe').innerHTML = document.getElementById('videos_comtpe').innerHTML + decodeEntities(unescape(responseArray[1].replaceAll("'", '"')));
							//document.getElementById('videos_comtpe').innerHTML = document.getElementById('videos_comtpe').innerHTML + decodeEntities(unescape(responseArray["data"].replaceAll("'", '"')));
                            offset = offset + parLoad;

                            setTimeout(loadNewVideos, 1000);

                        } else {
                            document.getElementById("newLoadnewVideo").style.display = "none";
                        }
                    }


                } else {
					//alert("pas json 09h46");
				}


            };

            xhr.send();
        }

        var decodeEntities = (function () {
            // this prevents any overhead from creating the object each time
            var element = document.createElement('div');

            function decodeHTMLEntities(str) {
                if (str && typeof str === 'string') {
                    // strip script/html tags
                    str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
                    str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
                    element.innerHTML = str;
                    str = element.textContent;
                    element.textContent = '';
                }

                return str;
            }

            return decodeHTMLEntities;
        })();

        function loadNewVideos() {

            if (canLoad) {
                if (elementInViewport(document.getElementById("newLoadnewVideo"))) {


                    if (caras) {
                        getVideosFromServer("&find=" + caras);
                    } else {
                        getVideosFromServer();
                    }


                    canLoad = false;
                } else { //retry after 1 sec
                    setTimeout(loadNewVideos, 1000);
                }
            }
        }

        function isJson(str) {
			console.log("String reçue pour analyse JSON zzz:", str);
            try {
                JSON.parse(str);
            } catch (e) {
                return false;
            }
            return true;
        }


        function elementInViewport(el) {
            if (el) {
                var top = el.offsetTop;
                var left = el.offsetLeft;
                var width = el.offsetWidth;
                var height = el.offsetHeight;

                while (el.offsetParent) {
                    el = el.offsetParent;
                    top += el.offsetTop;
                    left += el.offsetLeft;
                }

                return (
                    top < (window.pageYOffset + window.innerHeight) &&
                    left < (window.pageXOffset + window.innerWidth) &&
                    (top + height) > window.pageYOffset &&
                    (left + width) > window.pageXOffset
                );
            } else {
                return false;
            }
        }


        function stripScripts(s) {
            var div = document.createElement('div');
            div.innerHTML = s;
            var scripts = div.getElementsByTagName('script');
            var i = scripts.length;
            while (i--) {
                scripts[i].parentNode.removeChild(scripts[i]);
            }
            return div.innerHTML;
        }

    </script>
    </div>
{/block}