<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: 1000000,
  };

  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 / 1000000 })}
    {@html $t("main.supportedFormats", { supportedFormats: fileRequirements.supportedFormats.join(", ") })}
  </p>

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

  <input id="submit" 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>
  form {
    width: fit-content;
    margin: 0 auto;
  }
  .title-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  #submit {
    border: none;
    border-radius: 10px;
    padding: 15px
  }

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