<template>
  <div>
    <v-text-field
      :label="label"
      @click="clickInputTag"
      v-model="fileName"
      append-icon="attach_file"
    ></v-text-field>
    <input
      type="file"
      style="display: none"
      :id="id"
      :ref="reference"
      accept="image/*"
      @change="convertToBase64()"
    />
  </div>
</template> 
    <script >
export default {
  props: ["label", "reference", "id", "trigger"],
  data() {
    return {
      fileToLoad: "",
      fileName: "",
      fileInBase64: ""
    };
  },
  methods: {
    clickInputTag() {
      document.getElementById(this.id).click();
    },
    convertToBase64(e) {
      //Read File
      var selectedFile = document.getElementById(this.id).files;
      //Check File is not Empty

      if (selectedFile.length > 0) {
        // Select the very first file from list
        this.fileToLoad = selectedFile[0];
        this.fileName = selectedFile[0].name;
        console.log("file name - ", this.fileName);
        // FileReader function for read the file.
        var fileReader = new FileReader();
        // Onload of file read the file content
        let vm = this;
        fileReader.onload = function(fileLoadedEvent) {
          vm.fileInBase64 = fileLoadedEvent.target.result;
          // Print data in console
          console.log(vm.fileInBase64);

          var str = vm.fileInBase64;
          const [baseUrl, requiredUrl] = str.split(/,/);
          console.log("required - ", requiredUrl);

          let fileData = {
            fileName: this.fileName,
            fileInBase64: requiredUrl,
            trigger: ""
          };
          vm.$emit("fileSelected", fileData);
        };

        // Convert data to base64
        fileReader.readAsDataURL(this.fileToLoad);
      }
    },
    resetInput(params) {
      // RESET INPUT ELEMENT,fileName and selectedfile array

      this.$refs[this.reference].type = "text";
      this.$refs[this.reference].type = "file";
      this.fileName = "";
      this.fileToLoad = null;
      this.fileInBase64 = null;
      let fileData = {
        fileName: this.fileName,
        fileInBase64: this.fileInBase64,
        trigger: ""
      };
      this.$emit("fileSelected", fileData);
      console.log("its reset - ", fileData);
    }
  },
  watch: {
    respondToTrigger() {
      if (this.respondToTrigger == "reset") {
        console.log("Resets - ", this.trigger);
        this.resetInput();
      }
    }
  },
  computed: {
    respondToTrigger: {
      get() {
        return this.trigger;
      },
      set(newVal) {}
      // this.respondToTrigger = this.trigger;
    }
  }
};
</script> 
    <style scoped >
</style>