<template>
  <!--
    Everything is wrapped in a label, which acts as a clickable wrapper around a form element.
    In this case, the file input.
  -->
  <div class="field">
    <label class="label">{{lable}}</label>
    <div class="control">
      <label class="button">
        Select File
        <!-- Now, the file input that we hide. -->
        <input class="is-hidden" type="file" @change="handleFileChange" :accept="accept" />
      </label>
      <span v-if="filename">{{filename.name}}</span>
    </div>
  </div>
</template>


<script lang="ts">
import Vue from "vue";

const toBase64 = file =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });

export default {
  props: ["accept", "lable"],
  data: () => ({
    filename: null
  }),
  created() {
    this.filename = null;
  },
  methods: {
    async handleFileChange(e) {
      // Whenever the file changes, emit the 'input' event with the file data.
      this.$emit("input", await toBase64(e.target.files[0]));
      this.filename = e.target.files[0];
    }
  }
};
</script>
