<template>
	<fragment>
		<p class="more">
			<span>{{ t('Discover') }}</span>
			<NcSelect v-model="count"
				class="select"
				:components="Deselect"
				:options="[...Array(10).keys()].map(x=>(x+1)*10)"
				@input="fetch" />
		</p>
		<p>
			<NcLoadingIcon v-if="loading" />
			<ul v-if="!loading" class="tops">
				<li v-for="top in tops" :key="top.id">
					<TopItem :xml-url="top.xmlURL" :img-url="top.imgURL" :author="top.author" />
				</li>
			</ul>
			<span class="caption">{{ t('Suggests by fyyd') }}</span>
		</p>
	</fragment>
</template>

<script>
import { NcLoadingIcon, NcSelect } from '@nextcloud/vue'
import TopItem from './TopItem.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'TopList',
	components: {
		NcLoadingIcon,
		NcSelect,
		TopItem,
	},
	data() {
		return {
			tops: [],
			loading: true,
			count: 10,
			Deselect: {
				render: null,
			},
		}
	},
	async mounted() {
		await this.fetch()
	},
	methods: {
		async fetch() {
			this.loading = true

			try {
				const top = await axios.get(generateUrl('/apps/repod/top/{count}', { count: this.count }))
				this.tops = top.data.data
			} catch (e) {
				console.error(e)
				showError(t('Could not fetch tops'))
			}

			this.loading = false
		},
	},
}
</script>

<style scoped>
	.tops {
		display: flex;
		flex-wrap: wrap;
		gap: 2rem 5%;
		justify-content: center;
	}

	.tops li {
		flex-basis: 15%;
	}

	.select {
		min-width: 160px;
	}

	.more {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.caption {
		float: right;
		font-size: small;
		margin: .5rem;
	}
</style>
