<script>
  import CardList from "./CardList.svelte";
  import Dropzone from "./Dropzone.svelte";
  import FileList from "./FileList.svelte";

  import { filterFiles } from "../utils/filterFiles";
  import { supportedFormats } from "../format-readers";
  import { t } from "../i18n"

  let acceptedFiles;
  let rejectedFiles;
  let areAcceptedFilesRendered = false;
  const fileRequirements = {
    supportedFormats: Object.values(supportedFormats).map((f) => f.ext),
    maxSize: 700000,
  };

  const onSubmit = () => {
    areAcceptedFilesRendered = true;
  };

  const onDrop = (evt) => {
    onChange(evt);
  };

  const onChange = (evt) => {
    acceptedFiles = null;
    areAcceptedFilesRendered = false;

    const changedFiles = evt.dataTransfer
      ? evt.dataTransfer.files
      : evt.target.files;

    const results = filterFiles(changedFiles, fileRequirements);
    acceptedFiles = results.accepted;
    rejectedFiles = results.rejected;
  };

  const onClick = () => {
    document.getElementById("file-input").click();
  };

  const onKeydown = (evt) => {
    if (evt.key === "Enter") {
      document.getElementById("file-input").click();
    }
  };

</script>

<form
  id="form"
  enctype="multipart/form-data"
  on:submit|preventDefault|stopPropagation={onSubmit}
>
    <div class="title-container">
      <h2>{$t("main.title")}</h2>
    </div>
  <p>
    {@html $t("main.fileSize", { fileSize: fileRequirements.maxSize / 1000 })}
    {@html $t("main.supportedFormats", { supportedFormats: fileRequirements.supportedFormats.join(", ") })}
  </p>

  <Dropzone
    files={acceptedFiles}
    supportedFormats={fileRequirements.supportedFormats}
    {onKeydown}
    {onClick}
    {onDrop}
    {onChange}
  />

  <input type="submit" value={$t("main.render")} />
</form>

{#if areAcceptedFilesRendered}
  <CardList files={acceptedFiles} />
{:else}
  <FileList title={$t("main.selected")} files={acceptedFiles} />
  <FileList title={$t("main.rejected")} files={rejectedFiles} isError />
{/if}

<style>
  .title-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  @media only screen and (max-device-width: 812px) {
    #form {
      width: 100%;
    }
  }
</style>
