export default {
	setup() {
		const { ref, computed } = Vue;

		const currentPage = ref("");
		const pads = ref([]);
		const loaded = ref(false);

		const currentSort = ref("date");
		const currentSortDir = ref("desc");

		const sortedPads = computed(() => {
			return pads.value.sort((a, b) => {
				let modifier = 1;

				if (currentSortDir.value === "desc") modifier = -1;

				if (currentSort.value === "date") {
					a[currentSort.value] = new Date(a[currentSort.value]);
					b[currentSort.value] = new Date(b[currentSort.value]);
				}

				if (a[currentSort.value] < b[currentSort.value]) return -1 * modifier;
				if (a[currentSort.value] > b[currentSort.value]) return 1 * modifier;
				return 0;
			});
		});

		const formatDate = function (date) {
			return `${String(date.getDate()).padStart(2, "0")}-${String(
				date.getMonth() + 1
			).padStart(2, "0")}-${date.getFullYear()}`;
		};

		const sort = function (s) {
			if (s == currentSort.value) {
				currentSortDir.value = currentSortDir.value === "asc" ? "desc" : "asc";
			}
			currentSort.value = s;
		};

		const columns = ["title", "overview", "categories", "date"];

		// fetch("https://hub.xpub.nl/soupboat/padliography/")
		fetch("http://127.0.0.1:3147/")
			.then((res) => res.json())
			.then((data) => {
				pads.value = data.pads;
				currentPage.value = data.page;
				loaded.value = true;
			});

		return {
			pads,
			columns,
			sortedPads,
			currentPage,
			currentSort,
			currentSortDir,
			loaded,
			sort,
			formatDate,
		};
	},
	template: `

		<div v-if="!loaded" class='loading grow'>
			Loading loading loading loading loading loading loading loading loading loading loading loading loading loading loading loading loading loading etc
		</div>

		<div v-else>

			<p class="from">Fetching pads from <a :href="'https://pzwiki.wdka.nl/mediadesign/' + currentPage">
				{{currentPage}}
			</a>
			</p>
			
			
			<table>
				<tr class="header">
					<th v-for="column in columns" @click='sort(column)'> 
						{{column }}
						<span v-if='column == currentSort'> {{ currentSortDir == 'asc' ?  '▼' : '▲'}}</span>
						
					</th>
				</tr>
				<tr v-for="(pad, index) in sortedPads" key="pad.title, index" :class="pad.category">
					<td class="title">
						<a :href="pad.link" class='stretched' target="_blank"> {{pad.title}} </a>
					</td>
					<td class="overview">{{pad.overview}}</td>
					<td class="categories">{{pad.categories}}</td>
					<td class="date">{{formatDate(pad.date)}}</td>
					
				</tr>
			</table>
			</div>
			`,
};
