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

    <img alt="file upload" 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 class="text" v-if="total > 0">
      {{ current }} of {{ total }} files uploaded...
    </div>
  </div>
</template>

<script>
export default {
  name: "file-input",
  data: function () {
    return {
      drag: false,
      current: 0,
      total: 0
    }
  },
  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) {
      this.total += files.length;

      for (let file of files) {
        this.$root.socket.upload(`/projects/${this.$root.project.identifier}/data`, file)
            .then(() => this.current += 1);
      }
    }
  }
}
</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>