<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";
import locale from "$stores/locale";

let submission = "";

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

<InputTemplate
  field={$locale().reader?.mangaUrl ?? 'Manga URL'}
  bind:submission
  submitText={$locale().reader?.read ?? 'Read'}
  preserveCase
>
  {#if resourceIdentity}
    {#await fetchResource(submission)}
      <Message message={$locale().reader?.loadingChapters} />
    {: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>{$locale().reader?.fetchFailed}</Notice>
      {/if}
    {:catch}
      <Notice>{$locale().reader?.unknownError}</Notice>
    {/await}
  {:else}
    <Notice>{$locale().reader?.invalidUrl}</Notice>
  {/if}
</InputTemplate>
