<!--
  This file is part of vospace-ui
  Copyright (C) 2021 Istituto Nazionale di Astrofisica
  SPDX-License-Identifier: GPL-3.0-or-later
-->
<template>
<b-modal id="upload-files-modal" title="Upload file" okTitle="Upload" @show="reset" @ok.prevent="uploadFiles">
  <b-form-file v-model="files" :multiple="true" :state="fileState" placeholder="Choose your files or drop them here..." drop-placeholder="Drop files here..." @change="resetError"></b-form-file>
  <b-form-invalid-feedback id="upload-file-input-feedback" class="text-right">{{uploadFileError}}</b-form-invalid-feedback>
  <div class="mt-3">Selected files: {{ selectedFiles }}</div>
</b-modal>
</template>

<script>
const maxUploadSize = process.env.VUE_APP_MAX_UPLOAD_SIZE;

export default {
  data() {
    return {
      files: [],
      uploadFileError: null
    }
  },
  computed: {
    fileState() {
      if (this.uploadFileError) {
        return false;
      }
      return null;
    },
    selectedFiles() {
      if (this.files.length === 0) {
        return '';
      }
      let names = [];
      for (let file of this.files) {
        names.push(file.name);
      }
      return names.join(', ');
    }
  },
  methods: {
    reset() {
      this.files.splice(0, this.files.length);
      this.resetError();
    },
    resetError() {
      this.uploadFileError = null;
    },
    uploadFiles() {
      if (this.files.length === 0) {
        this.uploadFileError = "Select at least one file";
      } else {
        // Check special characters in file names
        for (let file of this.files) {
          if (/[<>?":\\/`|'*]/.test(file.name)) {
            this.uploadFileError = "File " + file.name + " contains an illegal character. Following characters are not allowed: < > ? \" : \\ / | ' * `";
            return;
          }
        }

        // Check size limit
        for (let file of this.files) {
          if (file.size >= maxUploadSize * Math.pow(10, 9)) {
            this.uploadFileError = "File " + file.name + " is too big. Max allowed file size is " + maxUploadSize + " GB";
            return;
          }
        }

        // Upload
        this.$store.dispatch('uploadFiles', this.files)
          .then(() => {
            this.$bvModal.hide('upload-files-modal');
          });
      }
    }
  }
}
</script>