<template>
	<div v-if="episode" class="footer">
		<audio id="audio-player"
			autoplay
			preload
			:src="episode.episodeUrl"
			@durationchange="duration = audio.duration"
			@ended="stop"
			@loadeddata="loadeddata"
			@pause="pause"
			@play="paused = false"
			@seeked="currentTime = audio.currentTime"
			@timeupdate="currentTime = audio.currentTime"
			@volumechange="volume = audio.volume" />
		<NcLoadingIcon v-if="loading" />
		<ProgressBar v-if="!loading"
			:current-time="currentTime"
			:duration="duration" />
		<div v-if="!loading" class="player">
			<img :src="episode.episodeImage">
			<Infos />
			<Controls :paused="paused" @stop="stop" />
			<Timer class="timer"
				:current-time="currentTime"
				:duration="duration" />
			<Volume class="volume" :volume="volume" />
		</div>
	</div>
</template>

<script>
import Controls from './Controls.vue'
import Infos from './Infos.vue'
import { NcLoadingIcon } from '@nextcloud/vue'
import ProgressBar from './ProgressBar.vue'
import Timer from './Timer.vue'
import Volume from './Volume.vue'
import axios from '@nextcloud/axios'
import { formatEpisodeTimestamp } from '../../utils/time.js'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'Bar',
	components: {
		Controls,
		Infos,
		NcLoadingIcon,
		ProgressBar,
		Timer,
		Volume,
	},
	data() {
		return {
			currentTime: 0,
			duration: 0,
			loading: true,
			paused: false,
			url: atob(this.$route.params.url),
			volume: 1,
		}
	},
	computed: {
		audio() {
			return document.getElementById('audio-player')
		},
		episode() {
			return this.$store.state.player.episode
		},
	},
	methods: {
		loadeddata() {
			this.loading = false

			if (this.episode.episodeAction) {
				this.audio.currentTime = this.episode.episodeAction.position
			}
		},
		pause() {
			this.paused = true
			this.track()
		},
		stop() {
			this.pause()
			this.$store.commit('player/play', null)
		},
		async track() {
			try {
				await axios.post(generateUrl('/apps/gpoddersync/episode_action/create'), [{
					podcast: this.url,
					episode: this.episode.episodeUrl,
					guid: this.episode.episodeGuid,
					action: 'play',
					timestamp: formatEpisodeTimestamp(new Date()),
					started: Math.round(this.episode.episodeAction ? this.episode.episodeAction.started : 0),
					position: Math.round(this.audio.currentTime),
					total: Math.round(this.audio.duration),
				}])
			} catch (e) {
				console.error(e)
				showError(t('Error while saving position on API'))
			}
		},
	},
}
</script>

<style scoped>
	.footer {
		background-color: rgba(66, 66, 66, .9);
		bottom: 0;
		height: 6rem;
		right: 0;
		position: absolute;
		width: 100%;
		z-index: 2000;
	}

	.player {
		display: flex;
		gap: 1rem;
		height: calc(6rem - 6px);
		justify-content: space-between;
	}

	.timer {
		width: 30%;
	}

	.volume {
		width: 10%;
	}
</style>
