<template>
    <div v-if="url" class="video-modal flex items-center justify-center z-50">
        <div class="video-modal__content m-4 relative">
            <div class="cursor-pointer text-right text-xl text-white mb-2" @click="close"><font-awesome-icon :icon="['fas', 'times']" /></div>
            <div class="videoWrapper">
                <iframe :src="url" width="420" height="315"></iframe>
            </div>
        </div>
    </div>
</template>

<script>
/**
 * Video Modal
 * 
 * On click of a video URL this modal should open
 * and begin playing the video.
 */
export default {
    data() {
        return {
            url: null
        }  
    },
    mounted() {
        document.addEventListener('click', this.interceptClickEvent);
    },
    destroyed() {
        document.removeEventListener('click', this.interceptClickEvent);
    },
    methods: {
        interceptClickEvent(e) {
            let target = e.target || e.srcElement;
            let closest = e.target.closest('a');
            if (!closest) return true;
            
            let href = closest.href || '';
            
            if (!href) return true;
            
            let type = this.videoType(href);
            if (!type)
                return true;
                
            // Convert youtube links to embed version
            if (type == 'youtube')
                href = '//www.youtube.com/embed/' + this.getYouTubeId(href);

            this.url = href;
            e.preventDefault();
        },
        videoType(url) {
            if (url.indexOf('youtube') !== -1 || url.indexOf('youtu.be') !== -1) {
                return 'youtube';
            } else if (url.indexOf('vimeo') !== -1) {
                return 'vimeo';
            } else {
                return false;
            }
        },
        getYouTubeId(url) {
            const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
            const match = url.match(regExp);
        
            return (match && match[2].length === 11)
              ? match[2]
              : null;
        },
        close() {
            this.url = null;
        }
    }
}
</script>

<style lang="scss" scoped>
.video-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba($black, .6);
    
    &__content {
        max-width: 900px;
        width: 100%;
    }
}

.videoWrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  height: 0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>