<template>
    <div
        v-if="content && getVideoData"
        class="audio-player overflow-hidden d-flex position-absolute vh-100 vw-100 justify-content-center align-items-center"
    >
        <transition mode="out-in" name="fade">
            <div class="audio-player-bg-image" :style="backGroundImage" />
        </transition>
        <template v-if="videoAssetData">
            <transition mode="out-in" name="fade">
                <video
                    v-show="showVideo"
                    ref="player"
                    class="player min-vh-100"
                    preload="metadata"
                    @timeupdate="videoTimeUpdate"
                    @canplay="videoCanPlay"
                    @ended="videoPlayedThrought"
                >
                    <source
                        :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>
        </template>
        <div
            class="fuggerei-code-audio position-absolute align-items-center vw-100 vh-100"
        >
            <h1 v-html="getLanguage(content.content.headline)"></h1>
            <div v-if="hasSubtitle" class="fuggerei-code-audio-body">
                <p
                    v-for="cap in currentCaption"
                    :key="'caption' + cap.text"
                    :style="{
                        animation: 'fadein ' + cap.time + 's',
                    }"
                    v-html="cap.text"
                ></p>
            </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: 'FuggerCodeAudio',
    components: {
        FuggerIcons,
        VideoProgressBar,
        FuggerButton,
    },
    props: {
        content: {
            type: Object,
            default: function() {
                return {}
            },
            required: true,
        },
        autoplay: {
            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,
            showVideo: false,
        }
    },
    computed: {
        backGroundImage() {
            console.log(this.content)
            if (
                this.content.content.audio[
                    this.$store.state.defaultLanguage.code
                ]?.posterAsset
            ) {
                return {
                    'background-image':
                        'url(' +
                        this.getAssetPath(
                            this.content.content.audio[
                                this.$store.state.defaultLanguage.code
                            ].posterAsset,
                        ) +
                        ')',
                }
            }
            return ''
        },
        getVideoData() {
            if (this.content.content.audio) {
                const vidData = this.getAssetData(
                    this.content.content.audio[
                        this.$store.state.defaultLanguage.code
                    ].audioAsset,
                )
                this.setVideoData(vidData)
                return vidData
            }
            return ''
        },
        hasSubtitle() {
            console.log(this.shortLanguage)
            if (this.content.content.audio[this.shortLanguage]?.subtitleAsset) {
                const subtitleId = this.content.content.audio[
                    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
        },
    },
    mounted() {
        eventbus.$on('closeVideo', this.videoEnd)
        eventbus.$on('closingVideo', event => {
            this.videoToggleVideo(event)
        })
        eventbus.$on('burgerMenuOpen', event => {
            this.videoToggleVideo(event)
        })
        eventbus.$emit('openoverlay', { type: 'audio' })
        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
        },
        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
            }

            this.showVideo = true

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

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

            if (this.videoPlayer) {
                if (this.videoCurrentTime === this.videoDurationtTime) {
                    this.videoPlayer.currentTime = 0.0
                } else {
                    this.videoPlayer.currentTime = this.videoCurrentTime
                }
                if (this.videoPlayer.paused) {
                    this.videoPlayer.play()
                }
            }
        },
        videoPausePlaying() {
            if (this.videoPlayer) {
                this.videoPlayer.pause()
                this.videoIsPLaying = false
            }
        },
        videoEnd() {
            this.videoIsPLaying = false
            this.removeGlobalEventbus()
            this.$emit('videoEnded')
        },
        videoPlayedThrought() {
            this.videoIsPLaying = false
            this.removeGlobalEventbus()
            setTimeout(() => {
                this.$emit('videoEnded')
            }, 3000)
        },
        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) {
                        console.log(cue)
                        const animTime = cue.endTime - cue.startTime
                        this.currentCaption.push({
                            time: animTime,
                            text: cue.text.replace('\n', '<br>'),
                        })
                    }
                }
            }
        },
        setSubtitle(caption) {
            this.caption = caption
        },
    },
}
</script>

<style lang="scss">
.audio-player {
    display: inline-block;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 100;
    position: absolute;
    background: var(--app-background-color);
}

.audio-player-bg-image {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
}

.fuggerei-code-audio {
    z-index: 100;
    padding-top: calc(220vw * var(--pxToVw));
    padding-left: calc(60vw * var(--pxToVw));
    padding-right: calc(400vw * var(--pxToVw));
    h1,
    .h1 {
        color: var(--primary);
        font-weight: 700;
        font-size: calc(80vw * var(--pxToVw));
        line-height: calc(72.48vw * var(--pxToVw));
        margin-bottom: calc(60vw * var(--pxToVw));
    }
    .fuggerei-code-audio-body {
        p,
        .p {
            font-weight: 400 !important;
            font-size: calc(60vw * var(--pxToVw)) !important;
            line-height: calc(70vw * var(--pxToVw)) !important;
        }
    }
    .video-progress-bar {
        position: absolute;
        width: 100vw;
        bottom: 0;
        left: 0;
    }
}

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

::cue {
    visibility: hidden;
}

@keyframes fadein {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}
</style>
