export default {
  name: 'r-file-loader',
  props: {
    supportedFile: {
      type: String,
      default: '.csv',
    },
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dragging: false,
      results: null,
    };
  },
  methods: {
    handleFileInput(event) {
      this.processFileInput(event.target.files);
      event.target.value = '';
    },
    handleDragOver(event) {
      event.stopPropagation();
      event.preventDefault();
      this.dragging = event.type === 'dragover';
      event.dataTransfer.dropEffect = 'copy';
    },
    handleFileSelect(event) {
      event.stopPropagation();
      event.preventDefault();
      this.dragging = false;
      this.processFileInput(event.dataTransfer.files);
    },
    processFileInput(files) {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const [ext] = file.name.match(/.[a-z0-9]+$/i) || [];
        console.log(file, file.type, ext);
        if (ext.match(this.supportedFile)) {
          const reader = new FileReader();
          reader.onloadend = function () {
            if (this.results === null) this.results = [];
            const results = {
              fileName: file.name,
              fileSize: file.size,
              file: file,
              fileExt: ext,
            };
            this.results.push(results);
            this.$emit('handleInput', results);
            this.$emit('input', results);
          }.bind(this);
          reader.readAsDataURL(file);
        }
      }
    },
    clearResults() {
      this.results = null;
    },
    clickInput() {
      this.$refs.fileInput.click();
    },
  },
};
