/**
 * Support multiple uploads
 */
import { mapActions, mapMutations } from 'vuex'

export default {
  data: () => ({
    params: {},
    files: [],
  }),
  methods: {
    ...mapActions(['getUploadSettings', 'doUpload']),
    ...mapMutations({
      resetUploader: 'RESET_UPLOADS',
    }),
    uploaderSettings() {
      if (Object.keys(this.params).length > 0) {
        this.getUploadSettings(this.params)
      }
    },
    async uploader(name) {
      this.resetUploader()
      let formData = new FormData()
      if (this.files.length > 0) {
        for (let i = 0; i < this.files.length; i++) {
          formData.append('file', this.files[i])
          formData.append('file_type', this.params.file_type)
          formData.append('uploader_name', name)
          await this.doUpload(formData).then(result => {
            if (!result || result.error) {
              let error = {
                title: this.$t('Common.Upload.Fail.Title'),
                description:
                  result.error ||
                  this.$t('Common.Upload.Fail.Description', { limit: process.env.VUE_APP_UPLOAD_FILE_SIZE_LIMIT }),
              }
              if (!window.navigator.onLine) {
                error = {
                  title: this.$t('Common.InternetConnection.Fail.Title'),
                  description: this.$t('Common.InternetConnection.Fail.Description'),
                }
              }
              this.$swal({
                title: error.title,
                text: error.description,
                type: 'error',
                confirmButtonText: this.$t('Common.TryAgain'),
              })
            }
          })
        }
      }
    },
  },
}
