<template>
  <div class="file-input"
       :class="{ active: drag }"
       @dragenter="dragenter"
       @dragleave="dragleave"
       @drop="drop">
    <input type="file"
           multiple
           @change="change">

    <img src="@/assets/icons/package-dependencies.svg">
    <div class="text">
      Click or drop a file here to upload it to the current project directory.
    </div>
  </div>
</template>

<script>
export default {
  name: "file-input",
  props: ['url'],
  data: function() {
    return {
      drag: false
    }
  },
  methods: {
    change: function(event) {
      event.preventDefault();
      this.drag = false;

      const result = [];
      for (let i = 0; i < event.target.files.length; i++) {
        result.push(event.target.files[i]);
      }

      this.upload(result);
    },
    dragenter: function(event) {
      event.preventDefault();
      this.drag = true;
    },
    dragleave: function(event) {
      event.preventDefault();
      this.drag = false;
    },
    drop: function(event) {
      event.preventDefault();
      this.drag = false;

      if (event.dataTransfer.items) {
        const result = [];
        for (let i = 0; i < event.dataTransfer.items.length; i++) {
          if (event.dataTransfer.items[i].kind === 'file') {
            const file = event.dataTransfer.items[i].getAsFile();
            result.push(file);
          }
        }

        this.upload(result);
      }
    },
    upload: function(files) {
      for (let file of files) {
        const form = new FormData();
        form.append('file', file);
        form.append('size', file.size);

        fetch(this.url, {
          method: 'POST',
          body: form
        })
            .then(() => console.log('done'))
            .catch(e => console.log(e));
      }
    }
  }
}
</script>

<style scoped>
.file-input {
  position: relative;

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 2rem;

  border: 1px dashed var(--primary);
  border-radius: 1rem;

  transition: background-color 2s, color 1s;
}

.file-input.active {
  background-color: var(--primary);
  color: white;
}

input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  z-index: 9;
  opacity: 0;
}

img {
  width: 3rem;
  margin-bottom: 1rem;
  opacity: 0.6;
  transition: opacity 1s, filter 1s;
}

.file-input.active img {
  opacity: 1;
  filter: invert(1);
}
</style>