<template>
	<FullScreenLoader v-if="loading" />

	<div id="archive">
		<h1>Archív vyriesenych BUG reportov</h1>

		<div class="reports">
			<div
				class="report-row"
				v-for="report in reports"
				:key="report.report_id"
				@click="$router.push('/report/' + report.report_id)"
			>
				<div class="report-id">
					<font-awesome-icon :icon="['fas', 'hashtag']" />
					{{ report.report_id }}
				</div>
				<div class="title">{{ report.report_title }}</div>
				<div class="date">{{ report.created_dt }}</div>
				<div class="group">{{ report.report_group }}</div>
			</div>
		</div>

		<div class="loadmore">
			<button v-if="!loadedAll" @click="loadMoreReports"><font-awesome-icon :icon="['fas', 'arrow-down']" /> Nacitat dalsie</button>
			<div v-else><font-awesome-icon :icon="['fas', 'check']" /> Vsetky archivovane reporty su zobrazene</div>
		</div>

	</div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from "vue";
import backend from "../backend";
import FullScreenLoader from "../components/FullScreenLoader.vue";

const reports = ref([]);
const loading = ref(false);
const page = ref(0);
const loadedAll = ref(false);

function loadMoreReports() {
	loading.value = true;
	backend.getArchived(page.value).then((response) => {
		// console.log(data);
		if (response.data.length == 0) {
			loadedAll.value = true;
		} else {
			reports.value.push(...response.data);
		}
		page.value++;
		loading.value = false;
	});
}

let _in_scroll_handler = false;
function handleScroll() {
	if (_in_scroll_handler || loading.value || loadedAll.value) return;
	_in_scroll_handler = true;
	const scrollY = window.scrollY;
	const windowHeight = window.innerHeight;
	const documentHeight = document.documentElement.scrollHeight;
	if (scrollY + windowHeight >= documentHeight - 100) {
		loadMoreReports();
	}
	_in_scroll_handler = false;
}

onMounted(() => {
	loadMoreReports();
	window.addEventListener("scroll", handleScroll);
});

onBeforeUnmount(() => {
	window.removeEventListener('scroll', handleScroll)
});

</script>
