<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'
  };

  const fetch_things = async (first_number) => {
      const file = fetch(url.root + url.files + "?p=" + Math.random())
	    .then(resp => resp.text())
	    .then(data => data.split('\n'));
      const thumb = fetch(url.root + url.thumb + url.files + "?q=" + Math.random())
	    .then(resp => resp.text())
	    .then(data => data.split('\n'));
      const out = await Promise.all([file, thumb]);

      // If we only want to get first N
      if(first_number) {
	  (out[0].length > first_number && (out[0].length = first_number));
      }
      
      return {file: out[0], thumb: out[1]};
  }
  
  onMount(async () => {
      const file_lists = await fetch_things();

      const thumbs_resolved = {};

      for(const thumb of file_lists.thumb)
      {
	  thumbs_resolved[thumb] = true;
      }

      file_list = [];

      // Loop backwards efficiently.
      for (let i = 0; i < file_lists.file.length; i++) {
	  const file = file_lists.file[i];
	  
	  if (/^\s*$/.test(file)) continue;

	  // Thumbs are only ever .jpg
	  const thumb_name = file.substr(0, file.lastIndexOf('.')) + '.jpg';
	  if (thumbs_resolved[thumb_name]) {
	      thumb_list.push(thumb_name);
	      file_list.push(file);
	  }
      }
      thumb_list = thumb_list.reverse();
  });
  
  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 loading="lazy" 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} />
