<template>
	<div>
		<Loading v-if="loading" />
		<ul v-if="!loading">
			<NcListItem v-for="feed in feeds"
				:key="feed.link"
				:details="formatLocaleDate(new Date(feed.fetchedAtUnix*1000))"
				:name="feed.title"
				:to="toUrl(feed.link)">
				<template #icon>
					<NcAvatar :display-name="feed.author"
						:is-no-user="true"
						:url="feed.imageUrl" />
				</template>
				<template #subname>
					{{ feed.author }}
				</template>
			</NcListItem>
		</ul>
	</div>
</template>

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

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