<script>
  import api from "../utilities/api";
  import { getNotificationsContext } from "svelte-notifications";
  const { addNotification } = getNotificationsContext();
  import notificationObject from "../utilities/notification";
  import { navigate } from "svelte-routing";

  let files = [];
  let slot;

  async function handleSubmit() {
    if (files.length > 0) {
      addNotification(
        notificationObject({
          text: "Uploading your excellent content ...",
        })
      );

      const formData = new FormData();
      formData.append("file", files[0]);
      formData.append("slot", slot);
      api()
        .post("/memes", formData)
        .then(() => {
          addNotification(
            notificationObject({
              text: "Your meme has been successfully uploaded!",
              type: "success",
            })
          );
          navigate("/", { replace: true });
        })
        .catch(() => {
          addNotification(
            notificationObject({
              text:
                "We weren't able to upload your meme. Please try again later",
              type: "danger",
            })
          );
        });
    }
  }
</script>

<div class="column is-4 is-offset-one-quarter">
  <h1 class="title">Upload</h1>
  <br />

  <form on:submit|preventDefault={handleSubmit}>
    <div class="file">
      <label class="file-label">
        <input
          class="file-input"
          accept=".png,.jpg,.jpeg"
          required
          id="file"
          type="file"
          bind:files
        />
        <span class="file-cta">
          <span class="file-icon">
            <i class="fas fa-upload" />
          </span>
          <span class="file-label">Choose a file </span>
        </span>

        {#if files.length > 0}
          <span class="file-name">
            {files[0].name}
          </span>
        {/if}
      </label>
    </div>

    <br />

    <div class="field">
      <label class="label" for="slot">Slot number within MegaMeme</label>
      <div class="control select">
        <select bind:value={slot}>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
          <option>7</option>
          <option>8</option>
          <option>9</option>
          <option>10</option>
          <option>11</option>
          <option>12</option>
          <option>13</option>
          <option>14</option>
          <option>15</option>
          <option>16</option>
        </select>
      </div>

      <p class="help">The slot numbers are from upper left to bottom right</p>
    </div>

    <input class="button is-primary" type="submit" />
  </form>
</div>

<br />
<footer class="footer">
  <div class="content has-text-centered">
    <p>
      <strong>MegaMeme</strong> | Copyright &#169; 2021 by L.Ceriani, A.Pfister &#38;
      M.Brändli
    </p>
  </div>
</footer>
