const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
var old_timestamp = document.getElementById('ts_reference').value;

function initPreviews() {
    var thumbs = document.querySelectorAll('div[data-thumbs]');
    thumbs.forEach(function (thumb) {
        var thumbsJSON = JSON.parse(thumb.dataset.thumbs);
        var originalImage = thumb.children[0].children[1].src;
        var interval;
        var i = 1;

        function clear() {
            thumb.children[0].children[1].src = originalImage;
            i = 1;
            clearTimeout(interval);
        }

        function toggle() {
            if (i == 0) {
                clear();
                return;
            }

            thumb.children[0].children[1].src = thumbsJSON[i];
            i = (i + 1) % thumbsJSON.length;
        }

        function interval() {
            // Start Preview
            interval = setInterval(toggle, 700);
        }

        thumb.addEventListener('mouseenter', interval);
        thumb.addEventListener('mouseleave', clear);
    });
}

async function init() {
    for (let i = 0; i < 9; i++) {
        var new_timestamp = document.getElementById('ts_reference').value;
        if (new_timestamp != old_timestamp) {
            console.log('== Changed ==');
            initPreviews();
            break;
        }
        console.log('== Didnt Change ==');
        await sleep(1000);
    }
}

window.addEventListener('contentChanged', event => {
    console.log('== Received contentChanged Event ==');
    init();
});

initPreviews();