class Slideshow {
    constructor(container, sliderArray, folder, autoplay, endless, random) {
        this.container = container
        this.sliderArray = sliderArray
        this.autoplay = autoplay
        this.endless = endless
        this.random = random
    }
}

class Slider {
    constructor(collectionId, collectionName, created, duration, enabled, id, media, updated) {
        this.collectionId = collectionId
        this.collectionName = collectionName
        this.created = created
        this.duration = duration
        this.enabled = enabled
        this.id = id
        this.media = media
        this.updated = updated
    }
}

let counter = 0;
let all = 0;
let restart, speed, wrapper, first, last, timeout, unusedPictureArray, random, autoIncrease, hash, slideshow, wrapper_blur;

async function startSlideShow(slideshowVariable) {
    slideshow = slideshowVariable;

    if ((typeof slideshow) === 'object') {
        let styles = document.createElement('link');
        styles.rel = "stylesheet";
        styles.href = "/css/slideshow.css";
        document.head.appendChild(styles);
        document.querySelector(slideshow.container).innerHTML = `<div id="image_blur"></div><div id="image"></div>`;
        wrapper = document.querySelector('#image');
        wrapper_blur = document.querySelector('#image_blur');
        hash = 'counter';

        if (!isNaN(localStorage.getItem(hash))) {
            counter = localStorage.getItem(hash)
        }
        autoIncrease = slideshow.autoplay;
        restart = slideshow.endless;

        if (slideshow.random === 0) {
            random = false;
            console.debug("random is false");
        } else {
            random = true;
            console.debug("random is true");
        }

        first = 0;
        last = slideshow.sliderArray.length - 1;
        timeout = false;
        speed = slideshow.speed || 12000;
        all = slideshow.sliderArray.length;
        unusedPictureArray = Array.from(Array(all).keys());

        document.addEventListener('keyup', ev => {
            ev.preventDefault();
            if (ev.key === "ArrowRight") {
                console.debug("Nächstes Bild");
                nextSlide();
            }
            if (ev.key === "ArrowUp") {
                history.back();
            }
            if (ev.key === "ArrowLeft") {
                console.debug("Vorheriges Bild");
                previousSlide();
            }
            if (ev.key === " ") {
                toggleAuto();
            }
        });
        validateCounter();
    } else {
        console.error('Please define a slideshow object first');
        document.body.innerHTML = "Kein gültiges SlideShow Objekt"
    }

}

function validateCounter() {
    localStorage.setItem(hash, counter);

    if (restart) {
        if (counter < 0) {
            counter = all - 1;
        } else {
            counter = counter % all;
        }

    } else {
        if (counter <= 0) {
            counter = 0;
        }
        if (counter === all){
            counter = all - 1;
        }
    }
    if (!restart) {
        first = counter === 0;
        last = counter === all - 1;
    }
    localStorage.setItem(hash, counter);
    show();
}

function show() {
    clearTimeout(timeout);
    wrapper.innerHTML = '';
    wrapper_blur.innerHTML = '';
    wrapper.dataset.loaded = 'false';  /* zeigt nen lade symbol*/
    speed = slideshow.sliderArray[counter].duration;

    if (slideshow.sliderArray[counter].media.endsWith('.html')) {
        wrapper.style.backgroundImage = ``;
        wrapper.id = "image";
        const makeIframe = document.createElement("iframe");
        makeIframe.setAttribute('src', "/api/files/" + slideshow.sliderArray[counter].collectionId + "/" + slideshow.sliderArray[counter].id + "/" + slideshow.sliderArray[counter].media);
        makeIframe.setAttribute("scrolling", "no");
        makeIframe.style.width = "100%";
        makeIframe.style.height = "100vh";
        makeIframe.style.overflow = "hidden";
        makeIframe.style.border = "none";
        makeIframe.style.position = "relative";
        makeIframe.style.zIndex = "7";
        wrapper_blur.style.height = "0";

        if (wrapper.dataset.loaded === 'false') {
            wrapper.dataset.loaded = 'true';
            wrapper.appendChild(makeIframe);
            loaded();
        }
    } else {
        if (slideshow.sliderArray[counter].media.endsWith('.mp4')) {
            wrapper.style.backgroundImage = ``;
            wrapper.id = "image";
            const vid = document.createElement('video');
            vid.setAttribute('loop', 'true');
            vid.setAttribute('autoplay', 'true');
            vid.muted = true;
            vid.style.height = `100%`;
            vid.style.display = `block`;
            vid.style.margin = `0 auto`;
            wrapper_blur.style.background = ``;
            wrapper.style.background = ``;
            vid.setAttribute('src', "/api/files/" + slideshow.sliderArray[counter].collectionId + "/" + slideshow.sliderArray[counter].id + "/" + slideshow.sliderArray[counter].media);
            if (wrapper.dataset.loaded === 'false') {
                vid.addEventListener('canplaythrough', () => {
                    wrapper.appendChild(vid);
                    loaded();
                }, {passive: true});
            }
        } else {
            wrapper.innerHTML = ' ';
            wrapper.id = "image";
            wrapper_blur.style.height = "100%";
            let url = '/api/files/' + slideshow.sliderArray[counter].collectionId + "/" + slideshow.sliderArray[counter].id + "/" + slideshow.sliderArray[counter].media;
            let i = new Image();
            i.src = url;
            i.onload = function () {
                wrapper.style.background = `url(${url}) no-repeat center`; //50% 50% no-repeat
                wrapper.style.backgroundSize = `contain`;

                wrapper_blur.style.background = `url(${url}) 50% 50% no-repeat`;
                wrapper_blur.style.backgroundSize = `cover`;
                loaded();
            }
        }
    }
}

function loaded() {
    wrapper.dataset.loaded = 'true';
    if (random) {
        timeout = window.setTimeout(function () {
            counter = randomPictureFromArray();
            localStorage.setItem(hash, counter);
            show();
        }, speed);
    } else {
        if (autoIncrease) {
            if (counter !== last) {
                timeout = window.setTimeout(function () {
                    counter++;
                    validateCounter();
                }, speed);
            } else {
                timeout = window.setTimeout(function () {
                    counter = 0;
                    validateCounter();
                }, speed);
            }
        }
    }
}

function nextSlide() {
    if (counter !== last) {
        // Nächstes Bild
        counter++;
        autoIncrease = false;
        validateCounter();
    } else {
        // Wenn letztes dann von vorne
        counter = 0;
        autoIncrease = false;
        validateCounter();
    }
}

//Vorheriges Bild
function previousSlide() {
    if (counter !== first) {
        counter--;
        autoIncrease = false;
        validateCounter();
    }
}

//Automatisches Abspielen anhalten / fortsetzen
function toggleAuto() {
    autoIncrease = !autoIncrease;
    random = !random;
    validateCounter();
}

function randomPictureFromArray() {
    if (unusedPictureArray.length < 1) {
        unusedPictureArray = Array.from(Array(all).keys());
    }
    let randomNumber = randomIntFromInterval(0, unusedPictureArray.length - 1);
    let imageNumber = unusedPictureArray[randomNumber];

    if (unusedPictureArray.length > 1) {
        while (imageNumber === counter) {
            randomNumber = randomIntFromInterval(0, unusedPictureArray.length - 1);
            imageNumber = unusedPictureArray[randomNumber];
        }
    }
    console.debug("Bildnummer: " + imageNumber);
    unusedPictureArray.splice(randomNumber, 1);
    return imageNumber;
}


function randomIntFromInterval(min, max) { // min and max included
    return Math.floor(Math.random() * (max - min + 1) + min);
}