<template>
	<NcAppNavigationItem :name="t('repod', 'Import subscriptions')" @click="modal = true">
		<template #extra>
			<NcModal v-if="modal" @close="modal = false">
				<div class="modal">
					<h2>{{ t('repod', 'Import OPML file') }}</h2>
					<form v-if="!loading"
						:action="generateUrl('/apps/repod/opml/import')"
						enctype="multipart/form-data"
						method="post"
						@submit.prevent="importOpml">
						<input accept="application/xml,.opml"
							name="import"
							required
							type="file">
						<input type="submit">
					</form>
					<Loading v-if="loading" />
				</div>
			</NcModal>
		</template>
		<template #icon>
			<ImportIcon :size="20" />
		</template>
	</NcAppNavigationItem>
</template>

<script>
import { NcAppNavigationItem, NcModal } from '@nextcloud/vue'
import ImportIcon from 'vue-material-design-icons/Import.vue'
import Loading from '../Atoms/Loading.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export default {
	name: 'Import',
	components: {
		ImportIcon,
		Loading,
		NcAppNavigationItem,
		NcModal,
	},
	data() {
		return {
			loading: false,
			modal: false,
		}
	},
	methods: {
		generateUrl,
		async importOpml(event) {
			try {
				const formData = new FormData(event.target)
				this.importLoading = true
				await axios.post(event.target.action, formData)
			} catch (e) {
				console.error(e)
			} finally {
				location.reload()
			}
		},
	},
}
</script>

<style scoped>
	.modal {
		align-items: center;
		display: flex;
		flex-direction: column;
		margin: 2rem;
	}
</style>
