<template>
	<NcContent app-name="repod">
		<NcAppNavigation>
			<NcAppContentList>
				<router-link to="/discover">
					<NcAppNavigationNew :text="t('repod', 'Add a podcast')">
						<template #icon>
							<Plus size="20" />
						</template>
					</NcAppNavigationNew>
				</router-link>
				<NcLoadingIcon v-if="loading" />
				<ul v-if="!loading">
					<NcAppNavigationItem v-for="subscription in subscriptions"
						:key="subscription.id"
						:loading="subscription.loading"
						:title="subscription.title ?? subscription.url">
						<template #icon>
							<img :src="subscription.imageUrl" alt="">
						</template>
					</NcAppNavigationItem>
				</ul>
			</NcAppContentList>
		</NcAppNavigation>
		<NcAppContent>
			<router-view />
		</NcAppContent>
	</NcContent>
</template>

<script>
import '@nextcloud/dialogs/dist/index.css'
import {
	NcAppContent,
	NcAppContentList,
	NcAppNavigation,
	NcAppNavigationItem,
	NcAppNavigationNew,
	NcContent,
	NcLoadingIcon,
} from '@nextcloud/vue'
import Plus from 'vue-material-design-icons/Plus.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'App',
	components: {
		NcAppContent,
		NcAppContentList,
		NcAppNavigation,
		NcAppNavigationItem,
		NcAppNavigationNew,
		NcContent,
		NcLoadingIcon,
		Plus,
	},
	data() {
		return {
			subscriptions: [],
			loading: true,
		}
	},
	computed: {
	},
	async mounted() {
		try {
			const metrics = await axios.get(generateUrl('/apps/gpoddersync/personal_settings/metrics'))
			for (const subscriptionId in metrics.data.subscriptions) {
				this.addSubscription({
					id: subscriptionId,
					url: metrics.data.subscriptions[subscriptionId].url,
					loading: true,
				})
			}
			for (const subscription of this.subscriptions) {
				this.updateSubscriptionMeta(subscription)
			}
		} catch (e) {
			console.error(e)
			showError(t('repod', 'Could not fetch subscriptions'))
		}
		this.loading = false
	},
	methods: {
		addSubscription(subscription) {
			const subscriptionId = this.subscriptions.findIndex(sub => sub.url === subscription.url)

			if (subscriptionId === -1) {
				this.subscriptions.push(subscription)
			} else {
				this.subscriptions[subscriptionId] = subscription
			}

			this.subscriptions.sort((a, b) => {
				if (a.title && b.title) return a.title.localeCompare(b.title)
				return a.id - b.id
			})
		},
		async updateSubscriptionMeta(subscription) {
			try {
				const podcasts = await axios.get(generateUrl('/apps/gpoddersync/personal_settings/podcast_data?url={url}', { url: subscription.url }))
				this.addSubscription({ ...podcasts.data.data, ...subscription, ...{ loading: false } })
			} catch (e) {
				console.error(e)
			}
		},
	},
}
</script>
