<script>
	import { onMount } from 'svelte';
	import Lightbox from './lightbox.svelte';

	let file_list;
	let open;
	let thumb_list = [];

	const url = {
		root: 'https://wg.flanchan.moe/cake/',
		thumb: 'thumb/',
		files: 'filelist.txt'
	};
	
	onMount(async () => {
		file_list = await fetch(url.root + url.files)
			.then(resp => resp.text())
			.then(data => data.split('\n'));
		
		// Loop backwards efficiently.
		for (let i = file_list.length - 2; i >= 0; i--) {
			const file = file_list[i];

			// Thumbs are only ever .jpg
			thumb_list.push(file.substr(0, file.lastIndexOf('.')) + '.jpg');
		}
	});
	
	function open_lightbox(i) {
		// If `open' is already `i' updates aren't sent to lightbox.
		open = null; 
		open = i;	
	}
</script>

{#if file_list}
	<section class="flex flex-row justify-center flex-wrap">
		{#each thumb_list as thumb, i}
			<img class="m-1" on:click={() => open_lightbox(i)} src="{url.root}{url.thumb}{thumb}" />
		{/each}
	</section>
{/if}
<Lightbox open={open} url={url} images={file_list} />
