<template>
    <div
        v-if="content && getVideoData"
        class="video-player overflow-hidden d-flex position-absolute vh-100 vw-100 justify-content-center align-items-center"
        :style="backGroundImage"
    >
        <template v-if="videoAssetData">
            <transition mode="out-in" name="fade">
                <video
                    v-show="showVideo"
                    ref="player"
                    class="player min-vh-100"
                    preload="metadata"
                    :muted="hasAudio"
                    @timeupdate="videoTimeUpdate"
                    @canplay="videoCanPlay"
                    @ended="videoEnd"
                >
                    <source
                        :key="'video_source_' + videoAssetData.paths"
                        :src="
                            videoAssetData.paths.local
                                ? videoAssetData.paths.local
                                : videoAssetData.paths.url
                        "
                        :type="videoAssetData.filetype"
                    />
                    <track
                        v-if="caption"
                        :key="'trackkey_' + hasSubtitle"
                        :src="'data:text/vtt;base64,' + caption"
                        kind="subtitles"
                        :label="language"
                        default
                        :srclang="language"
                        @cuechange="subtitle"
                    />
                </video>
            </transition>
            <audio v-if="hasAudio" ref="audioPlayer" preload="metadata">
                <source
                    :key="'audio_language_' + language"
                    :src="getAudioUrl()"
                    type="audio/mpeg"
                />
            </audio>
        </template>
        <div
            class="video-player-bottom position-absolute flex-column align-items-center d-flex vw-100"
        >
            <transition mode="out-in" name="fade">
                <div
                    v-if="hasSubtitle && currentCaption.length > 0"
                    :key="currentCaption"
                    class="video-player-caption d-flex position-relative align-items-center"
                >
                    <h5 v-html="currentCaption"></h5>
                </div>
            </transition>
            <div class="video-player-controls align-items-center d-flex vw-100">
                <div class="video-controls">
                    <div
                        class="backward"
                        @click.prevent.stop="jump(videoPlayer.currentTime - 10)"
                    >
                        <fugger-button
                            theme="light"
                            type="backward-btn"
                        ></fugger-button>
                    </div>
                    <div
                        class="forward"
                        @click.prevent.stop="jump(videoPlayer.currentTime + 10)"
                    >
                        <fugger-button
                            theme="light"
                            type="forward-btn"
                        ></fugger-button>
                    </div>
                </div>
            </div>
            <div class="video-progress-bar">
                <video-progress-bar
                    :duration="videoDurationtTime"
                    :current-time.sync="videoCurrentTime"
                />
            </div>
        </div>
    </div>
</template>

<script>
import VideoProgressBar from './VideoProgressBar'
import FuggerButton from './FuggerButton.vue'
import { eventbus } from './index'
import FuggerIcons from './FuggerIcons'

export default {
    name: 'FuggerVideo',
    components: {
        FuggerIcons,
        VideoProgressBar,
        FuggerButton,
    },
    props: {
        content: {
            type: Object,
            default: function() {
                return {}
            },
            required: true,
        },
        autoplay: {
            type: Boolean,
            default: false,
            required: false,
        },
        hideOverlay: {
            type: Boolean,
            default: false,
            required: false,
        },
    },
    data() {
        return {
            currentCaption: '',
            caption: '',
            videoPlayer: null,
            videoAssetData: {},
            videoIsPLaying: false,
            videoControlBar: true,
            videoControlBarTimer: null,
            videoCurrentTime: 0,
            videoDurationtTime: 0,
            audioPlayer: null,
            audioAssetData: {},
            hasAudio: false,
            showVideo: false,
            hideInstructionOverlay: this.hideOverlay,
        }
    },
    computed: {
        backGroundImage() {
            if (
                this.content.fieldValues.video[
                    this.$store.state.defaultLanguage.code
                ]?.posterAsset
            ) {
                return {
                    'background-image':
                        'url(' +
                        this.getAssetPath(
                            this.content.fieldValues.video[
                                this.$store.state.defaultLanguage.code
                            ].posterAsset,
                        ) +
                        ')',
                }
            }
            return ''
        },
        getVideoData() {
            if (this.content.fieldValues.video) {
                const audioData = new Array()
                this.$store.state.languages.forEach(language => {
                    if (
                        this.content.fieldValues.video[language.code].audioAsset
                    ) {
                        const audioId = this.getAssetData(
                            this.content.fieldValues.video[language.code]
                                .audioAsset,
                        )
                        audioData.push({
                            lang: language.code,
                            asset: audioId,
                        })
                    }
                })
                this.setAudioData(audioData)
                const vidData = this.getAssetData(
                    this.content.fieldValues.video[
                        this.$store.state.defaultLanguage.code
                    ].videoAsset,
                )
                this.setVideoData(vidData)
                return vidData
            }
            return ''
        },
        hasSubtitle() {
            console.log(this.shortLanguage)
            if (
                this.content.fieldValues.video[this.shortLanguage]
                    ?.subtitleAsset
            ) {
                const subtitleId = this.content.fieldValues.video[
                    this.shortLanguage
                ].subtitleAsset
                const subtitle = this.getAssetPath(
                    subtitleId,
                    'conversion',
                    true,
                )
                this.setSubtitle(subtitle)
                return true
            }
            return false
        },
        language() {
            return this.$store.getters.currentLanguage
        },
        shortLanguage() {
            return this.$store.getters.currentShortLanguage
        },
        lang: () => start => {
            return start
        },
    },
    watch: {
        hideOverlay() {
            this.hideInstructionOverlay = this.hideOverlay
        },
        language() {
            if (this.hasAudio) {
                this.videoPlayer.pause()
                this.audioPlayer.pause()
                this.audioPlayer.children[0].src = this.getAudioUrl()
                this.audioPlayer.load()
                this.audioPlayer.currentTime = this.videoPlayer.currentTime
                if (this.videoIsPLaying) {
                    this.videoPlayer.play()
                    this.audioPlayer.play()
                }
            }
        },
    },
    mounted() {
        eventbus.$on('closeVideo', this.videoEnd)
        eventbus.$on('closingVideo', event => {
            this.videoToggleVideo(event)
        })
        eventbus.$on('burgerMenuOpen', event => {
            this.videoToggleVideo(event)
        })
        if (this.hideInstructionOverlay) {
            setTimeout(() => {
                this.videoStartPlaying()
            }, 150)
            setTimeout(() => {
                this.videoStartPlaying()
            }, 2500)
        } else {
            eventbus.$emit('openoverlay', { type: 'video' })
            eventbus.$on('closeoverlay', () => {
                eventbus.$off('closeoverlay')
                this.videoStartPlaying()
            })
        }
    },
    beforeDestroy() {
        this.removeGlobalEventbus()
    },
    methods: {
        removeGlobalEventbus() {
            eventbus.$off('closeVideo')
            eventbus.$off('closingVideo')
            eventbus.$off('burgerMenuOpen')
        },
        setVideoData(videoData) {
            this.videoAssetData = videoData
        },
        setAudioData(audioData) {
            this.hasAudio = true
            this.audioAssetData = audioData
        },
        getAudioUrl() {
            if (this.audioAssetData) {
                const url = this.getAudioAssetLanguage(this.audioAssetData)
                if (url) {
                    return url.asset.paths.local
                        ? url.asset.paths.local
                        : url.asset.paths.url
                }
                return null
            }
        },
        videoTimeUpdate() {
            if (this.videoPlayer) {
                this.videoCurrentTime = this.videoPlayer.currentTime
                this.videoDurationtTime = this.videoPlayer.duration
                this.$emit('videoIsPlaying')
            }
        },
        videoToggleVideo(toggleState) {
            if (toggleState) {
                this.videoPausePlaying()
            } else if (this.videoPlayer.paused) {
                this.videoStartPlaying()
            }
        },
        videoCanPlay() {
            if (!this.videoPlayer) {
                this.videoPlayer = this.$refs.player
            }
            if (this.hasAudio && !this.audioPlayer) {
                this.audioPlayer = this.$refs.audioPlayer
            }

            this.showVideo = true
            if (this.autoplay && !this.videoIsPLaying) {
                this.videoStartPlaying()
            }
        },
        videoStartPlaying() {
            if (this.videoIsPLaying && !this.videoPlayer.paused) {
                return
            }
            this.videoIsPLaying = true

            if (!this.videoPlayer) {
                this.videoPlayer = this.$refs.player
            }
            if (this.hasAudio && !this.audioPlayer) {
                this.audioPlayer = this.$refs.audioPlayer
            }

            if (this.videoPlayer) {
                if (this.videoCurrentTime === this.videoDurationtTime) {
                    this.videoPlayer.currentTime = 0.0
                    if (this.hasAudio) {
                        this.audioPlayer.currentTime = 0.0
                    }
                } else {
                    this.videoPlayer.currentTime = this.videoCurrentTime
                    if (this.hasAudio) {
                        this.audioPlayer.currentTime = this.videoCurrentTime
                    }
                }
                if (this.videoPlayer.paused) {
                    this.videoPlayer.play()
                    if (this.hasAudio) {
                        this.audioPlayer.play()
                    }
                }
            }
        },
        videoPausePlaying() {
            if (this.videoPlayer) {
                this.videoPlayer.pause()
                if (this.hasAudio) {
                    this.audioPlayer.pause()
                }
                this.videoIsPLaying = false
            }
        },
        videoEnd() {
            this.videoIsPLaying = false
            this.removeGlobalEventbus()
            this.$emit('videoEnded')
        },
        jump(time) {
            if (time > this.videoDurationtTime) {
                this.videoPlayer.currentTime = this.videoDurationtTime
                if (this.hasAudio) {
                    this.audioPlayer.currentTime = this.videoDurationtTime
                }
                return
            }
            this.videoPlayer.currentTime = time
            if (this.hasAudio) {
                this.audioPlayer.currentTime = time
            }
            this.currentCaption = ''
            this.subtitle()
        },
        subtitle() {
            for (let i = 0; i < this.videoPlayer.textTracks.length; i++) {
                const track = this.videoPlayer.textTracks[i]
                for (const cue of track.activeCues) {
                    if (cue.text.length > 0) {
                        this.currentCaption = cue.text.replace('\n', '<br>')
                    } else {
                        this.currentCaption = ''
                    }
                }
            }
        },
        setSubtitle(caption) {
            this.caption = caption
        },
    },
}
</script>

<style lang="scss">
@import 'assets/scss/variables';
@import 'assets/scss/buttons';
@import 'assets/scss/global';

.video-player {
    display: inline-block;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    z-index: 100;
    position: absolute;

    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;

    .player {
        object-fit: fill;
    }

    .video-player-caption {
        background-color: white;
        color: black;
        z-index: 100;
        position: absolute;
        bottom: calc(0vw * var(--pxToVw));
        height: calc(160vw * var(--pxToVw));
        padding-top: calc(10vw * var(--pxToVw));
        padding-left: calc(52vw * var(--pxToVw));
        padding-right: calc(52vw * var(--pxToVw));
        width: calc(62vw * var(--pxToVw));
        width: auto;

        h5 {
            margin: 0;
            line-height: calc(50vw * var(--pxToVw));
        }
    }
}

//noinspection CssInvalidPseudoSelector
::-webkit-media-text-track-display {
    display: none;
}

::cue {
    visibility: hidden;
}

.video-controls {
    position: fixed;
    left: calc(60vw * var(--pxToVw));
    bottom: calc(62vw * var(--pxToVw));
    z-index: 22222;
    display: flex;

    .backward,
    .forward {
        .backward-btn span,
        .forward-btn span {
            height: calc(80vw * var(--pxToVw));
            width: calc(80vw * var(--pxToVw));
        }
    }

    .backward {
        margin-right: calc(2vw * var(--pxToVw));
    }
}

.video-player-bottom {
    position: absolute;
    bottom: 0;
    display: block;
}
</style>
