<template>
	<NcAppNavigationItem :loading="loading"
		:name="feed ? feed.title : url"
		:to="hash">
		<template #icon>
			<NcAvatar v-if="feed"
				:display-name="feed.author || feed.title"
				:is-no-user="true"
				:url="feed.imageUrl" />
			<Alert v-if="failed" />
		</template>
		<template #actions>
			<NcActionButton @click="deleteSubscription">
				<template #icon>
					<Delete :size="20" />
				</template>
				{{ t('repod', 'Delete') }}
			</NcActionButton>
		</template>
	</NcAppNavigationItem>
</template>

<script>
import { NcActionButton, NcAppNavigationItem, NcAvatar } from '@nextcloud/vue'
import Alert from 'vue-material-design-icons/Alert.vue'
import Delete from 'vue-material-design-icons/Delete.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'
import { toUrl } from '../../utils/url.js'

export default {
	name: 'Item',
	components: {
		Alert,
		Delete,
		NcActionButton,
		NcAppNavigationItem,
		NcAvatar,
	},
	props: {
		url: {
			type: String,
			required: true,
		},
	},
	data() {
		return {
			failed: false,
			loading: true,
			feed: null,
		}
	},
	computed: {
		hash() {
			return toUrl(this.url)
		},
	},
	async mounted() {
		try {
			const podcastData = await axios.get(generateUrl('/apps/gpoddersync/personal_settings/podcast_data?url={url}', { url: this.url }))
			this.feed = podcastData.data.data
		} catch (e) {
			this.failed = true
			console.error(e)
		} finally {
			this.loading = false
		}
	},
	methods: {
		async deleteSubscription() {
			if (confirm(t('repod', 'Are you sure you want to delete this subscription?'))) {
				try {
					this.loading = true
					await axios.post(generateUrl('/apps/gpoddersync/subscription_change/create'), { add: [], remove: [this.url] })
				} catch (e) {
					console.error(e)
					showError(t('repod', 'Error while removing the feed'))
				} finally {
					this.loading = false
					this.$store.dispatch('subscriptions/fetch')
				}
			}
		},
	},
}
</script>