class Video {

    constructor(videoData) {
        this.videoID = videoData.id;
        this.shown = false;

        this.root = videoTemplate.content.cloneNode(true);
        this.item = this.root.querySelector(".video-item");
        this.closeButton = this.root.querySelector(".video-close");
        this.img = this.root.querySelector(".video-item .video-image");
        this.title = this.root.querySelector(".video-item .video-title");
        this.videoProgressPrimary = this.root.querySelector(".video-item .video-progress .primary");
        this.videoProgressSecondary = this.root.querySelector(".video-item .video-progress .secondary");

        this.item.addEventListener("click", this.enable.bind(this));
        this.closeButton.addEventListener("click", this.close.bind(this));

        this.update(videoData);
    }

    enable() {
        const currentDisplay = localStorage.getItem("display");
        if (this.videoData.display != currentDisplay) {
            showVideo(this.videoID, currentDisplay);
        } else {
            hideVideo(this.videoID);
        }
    }

    update(videoData) {
        if (videoData.id != this.videoID) {
            throw `tried to update video instance ${this.videoID} with data from video ${videoData.id}`;
        }

        this.videoData = videoData;

        const progressPercentage = videoData.progress / videoData.duration * 100;
        const bufferPercentage = videoData.buffered / videoData.duration * 100;

        this.img.src = videoData.metadata.thumbnail;
        this.title.textContent = videoData.title;
        this.videoProgressPrimary.style.width = `${progressPercentage}%`;
        this.videoProgressSecondary.style.width = `${bufferPercentage}%`;

        const currentDisplay = localStorage.getItem("display");
        if (videoData.display == currentDisplay) {
            this.img.classList.add("shown-on-display");
        } else {
            this.img.classList.remove("shown-on-display");
        }
    }

    shownOnDisplay() {
        const currentDisplay = localStorage.getItem("display");
        return this.videoData.display == currentDisplay;
    }

    show() {
        videoContainer.appendChild(this.item);
        this.shown = true;
    }

    showAt(index) {
        videoContainer.insertChildAtIndex(this.item, index);
        this.shown = true;
    }

    hide() {
        videoContainer.removeChild(this.item);
        this.shown = false;
    }

    close(event) {
        console.log(event);
        event.stopPropagation();
        askForCloseVideoConfirmation(this.videoID, this.videoData.title);
    }

}