import { parseVideo } from './parse-video-url';
import { onPageLoadComplete } from '@nimius/event-utility';

const videoElementAttribute = 'data-video';
const videoTriggerAttribute = 'data-video-trigger';
const videoIframeAttribute = 'data-video-iframe';
const videoSourceAttribute = 'data-video-src';

const initParseVideo = () => {
    for (const videoElement of document.querySelectorAll(`[${videoElementAttribute}]`)) {
        const videoTrigger = videoElement.querySelector(`[${videoTriggerAttribute}]`);
        const videoIframe = videoElement.querySelector(`[${videoIframeAttribute}]`);

        videoTrigger.addEventListener('click', (e) => {
            e.preventDefault();

            const videoObject = parseVideo(videoIframe.getAttribute(videoSourceAttribute));
            let videoSource = '';

            if (videoObject.type === 'youtube') {
                videoSource = `//www.youtube-nocookie.com/embed/${videoObject.id}?rel=0&amp;autoplay=1`;
            } else if (videoObject.type === 'vimeo') {
                videoSource = `//player.vimeo.com/video/${videoObject.id}?autoplay=1`;
            }

            videoIframe.src = videoSource;
            videoElement.classList.add('is-active');
        });
    }
};

onPageLoadComplete(() => {
    initParseVideo();
});
