<template>
	<fragment>
		<NcLoadingIcon v-if="loading" />
		<ul v-if="!loading">
			<NcListItem v-for="episode in episodes"
				:key="episode.episodeUrl"
				: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>
					{{ format(new Date(episode.episodeDuration*1000), 'H:mm:ss') }}
				</template>
				<template #actions>
					<NcActionButton>
						<template #icon>
							<Play :size="20" />
						</template>
						{{ t('Play') }}
					</NcActionButton>
				</template>
			</NcListItem>
		</ul>
	</fragment>
</template>

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

export default {
	name: 'List',
	components: {
		NcActionButton,
		NcAvatar,
		NcListItem,
		NcLoadingIcon,
		Play,
	},
	data() {
		return {
			episodes: [],
			loading: true,
		}
	},
	computed: {
		url() {
			return atob(this.$route.params.url)
		},
	},
	async mounted() {
		try {
			this.loading = true
			const episodes = await axios.get(generateUrl('/apps/repod/episodes?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: {
		format,
		formatTimeAgo,
	},
}
</script>
