<template>
	<NcAppNavigationItem :loading="loading"
		:title="title ?? subscriptionUrl">
		<template #icon>
			<img v-if="imageUrl"
				:src="imageUrl"
				:alt="title"
				width="20"
				height="20">
			<Alert v-if="failed" />
		</template>
		<template #actions>
			<NcActionButton @click="deleteSubscription">
				<template #icon>
					<Delete :size="20" />
				</template>
				{{ t('Delete') }}
			</NcActionButton>
		</template>
	</NcAppNavigationItem>
</template>

<script>
import { NcActionButton, NcAppNavigationItem } 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'

export default {
	name: 'SubscriptionListItem',
	components: {
		Alert,
		Delete,
		NcActionButton,
		NcAppNavigationItem,
	},
	props: {
		subscriptionUrl: {
			type: String,
			required: true,
		},
	},
	data() {
		return {
			failed: false,
			loading: true,
			title: null,
			imageUrl: null,
		}
	},
	async mounted() {
		try {
			const podcastData = await axios.get(generateUrl('/apps/gpoddersync/personal_settings/podcast_data?url={url}', { url: this.subscriptionUrl }))
			this.title = podcastData.data.data.title
			this.imageUrl = podcastData.data.data.imageUrl
		} catch (e) {
			this.failed = true
			console.error(e)
		} finally {
			this.loading = false
		}
	},
	methods: {
		async deleteSubscription() {
			try {
				this.loading = true
				await axios.post(generateUrl('/apps/gpoddersync/subscription_change/create'), { add: [], remove: [this.subscriptionUrl] })
			} catch (e) {
				console.error(e)
				showError(t('Error while removing the feed'))
			} finally {
				this.loading = false
				this.$store.dispatch('subscriptions/fetch')
			}
		},
	},
}
</script>
