<template>
	<ul>
		<NcListItem v-for="feed in feeds"
			:key="`${feed.provider}_${feed.id}`"
			:counter-number="feed.nb_episodes"
			:details="formatTimeAgo(new Date(feed.last_pub))"
			:title="feed.title"
			:to="`/${feed.feed_url}`">
			<template #icon>
				<NcAvatar :display-name="feed.author"
					:is-no-user="true"
					:url="feed.image" />
			</template>
			<template #subtitle>
				{{ feed.author }}
			</template>
			<template #indicator>
				<img :alt="feed.provider"
					height="15"
					:src="generateUrl(`/apps/repod/img/${feed.provider}.svg`)">
			</template>
		</NcListItem>
	</ul>
</template>

<script>
import { NcAvatar, NcListItem } from '@nextcloud/vue'
import axios from '@nextcloud/axios'
import { debounce } from '../utils/debounce.js'
import { formatTimeAgo } from '../utils/time.js'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'Search',
	components: {
		NcAvatar,
		NcListItem,
	},
	props: {
		value: {
			type: String,
			required: true,
		},
	},
	data() {
		return {
			feeds: [],
		}
	},
	watch: {
		value() {
			this.search()
		},
	},
	methods: {
		search: debounce(async function value() {
			try {
				const currentSearch = this.value
				const feeds = await axios.get(generateUrl('/apps/repod/search/{value}', { value: currentSearch }))
				if (currentSearch === this.value) {
					this.feeds = feeds.data
				}
			} catch (e) {
				console.error(e)
				showError(t('Could not fetch search results'))
			}
		}, 200),
		formatTimeAgo,
		generateUrl,
	},
}
</script>
