<script>
import Notice from "$lib/Error/Notice.svelte";
import Message from "$lib/Loading/Message.svelte";
import MangaDexChapters from "$lib/Reader/Chapters/MangaDex.svelte";
import RawkumaChapters from "$lib/Reader/Chapters/Rawkuma.svelte";
import {
	decodeResource,
	fetchResource,
	identify,
	Resource,
} from "$lib/Reader/resource";
import InputTemplate from "$lib/Tools/InputTemplate.svelte";

let submission = "";

$: resourceIdentity = identify(submission);
</script>

<InputTemplate field="Manga URL" bind:submission submitText="Read" preserveCase>
  {#if resourceIdentity}
    {#await fetchResource(submission)}
      <Message message="Loading chapters ..." />
    {:then response}
      {#if response.ok}
        {#await decodeResource(response, submission) then data}
          {#if resourceIdentity === Resource.MangaDex}
            <MangaDexChapters {data} />
          {:else if resourceIdentity === Resource.Rawkuma}
            <RawkumaChapters {data} />
          {/if}
        {:catch error}
          <Notice>{error}</Notice>
        {/await}
      {:else}
        <Notice>Failed to fetch data</Notice>
      {/if}
    {:catch}
      <Notice>An unknown error has occurred.</Notice>
    {/await}
  {:else}
    <Notice>Invalid URL</Notice>
  {/if}
</InputTemplate>
