<template>
	<div>
		<NcLoadingIcon v-if="loading" />
		<ul v-if="!loading" :style="{marginBottom: currentEpisode ? '6rem' : 'auto'}">
			<NcListItem v-for="episode in episodes"
				:key="episode.episodeGuid"
				:details="formatTimeAgo(new Date(episode.episodePubDate.date))"
				:force-display-actions="true"
				:name="episode.episodeName"
				:title="episode.episodeDescription">
				<template #icon>
					<NcAvatar :display-name="episode.episodeName"
						:is-no-user="true"
						:url="episode.episodeImage" />
				</template>
				<template #subname>
					{{ formatTimer(new Date(episode.episodeDuration*1000)) }}
				</template>
				<template #actions>
					<NcActionButton @click="isCurrentEpisode(episode) ? load(null) : load(episode)">
						<template #icon>
							<PlayButton v-if="!isCurrentEpisode(episode)" :size="20" />
							<StopButton v-if="isCurrentEpisode(episode)" :size="20" />
						</template>
						{{ isCurrentEpisode(episode) ? t('Stop') : t('Play') }}
					</NcActionButton>
				</template>
			</NcListItem>
		</ul>
	</div>
</template>

<script>
import { NcActionButton, NcAvatar, NcListItem, NcLoadingIcon } from '@nextcloud/vue'
import { formatTimeAgo, formatTimer } from '../../utils/time.js'
import PlayButton from 'vue-material-design-icons/Play.vue'
import StopButton from 'vue-material-design-icons/Stop.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'List',
	components: {
		NcActionButton,
		NcAvatar,
		NcListItem,
		NcLoadingIcon,
		PlayButton,
		StopButton,
	},
	data() {
		return {
			episodes: [],
			loading: true,
		}
	},
	computed: {
		currentEpisode() {
			return this.$store.state.player.episode
		},
		url() {
			return atob(this.$route.params.url)
		},
	},
	async mounted() {
		try {
			this.loading = true
			const episodes = await axios.get(generateUrl('/apps/repod/episodes/list?url={url}', { url: this.url }))
			this.episodes = episodes.data
		} catch (e) {
			console.error(e)
			showError(t('Could not fetch episodes'))
		} finally {
			this.loading = false
		}
	},
	methods: {
		formatTimer,
		formatTimeAgo,
		isCurrentEpisode(episode) {
			return this.currentEpisode && this.currentEpisode.episodeUrl === episode.episodeUrl
		},
		load(episode) {
			this.$store.dispatch('player/load', episode)
		},
	},
}
</script>
