<template>
  <div class="card mb-2">
    <header class="card-header">
      <h5 class="mb-0">Upload voucher codes (CSV/TXT)</h5>
    </header>
    <div class="card-body">
      <form @submit.prevent="submit">
        <field
          label="Bestand selecteren"
          info="Dit bestand moet in '.csv' of '.txt' formaat zijn."
          no-focus
        >
          <input
            @change="update"
            ref="file"
            type="file"
            accept=".txt, .csv"
            name="file"
            class="form-control-file"
          />
        </field>

        <field no-focus>
          <button
            :disabled="!containsFile || isLoading"
            v-text="
              isLoading
                ? 'Vouchers codes aan het uploaden...'
                : 'Upload voucher codes'
            "
            class="btn btn-primary"
          ></button>
        </field>
      </form>
    </div>

    <modal ref="uploadInfoModal" v-on:hide="onCloseModal" large>
      <header class="modal-header">
        <h3 class="modal-title">Upload informatie</h3>
        <button
          type="button"
          class="close"
          @click.prevent="closeModal"
          aria-label="Close"
        >
          <span aria-hidden="true">&times;</span>
        </button>
      </header>
      <div class="modal-body">
        <div v-if="responseData">
          <p>
            Het nieuwe bestand bevat {{ responseData.uploadCount }} codes,
            hiervan zijn er {{ responseData.addedCount }} toegevoegd.
          </p>
          <p>
            In totaal zijn {{ responseData.totalCount }} toegevoegd aan deze
            actie.
          </p>
        </div>
      </div>
    </modal>
  </div>
</template>

<script>
 import { handleFetch } from '../api/helpers';
 import field from "../shared/form/field.vue";
 import modal from "../shared/modal.vue";

export default {
  props: {
    uploadUrl: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      isLoading: false,
      selectedCsv: null,
      responseData: {},
    };
  },
  methods: {
    update() {
      this.selectedCsv = this.$refs.file.files[0];
    },
    resetForm() {
      this.$refs.file.value = null;
      this.selectedCsv = this.$refs.file.files[0];
    },
    async submit(e) {
      try {
        this.isLoading = true;

        const response = await handleFetch(this.uploadUrl, {
          method: 'post',
          body: new FormData(e.target),
          credentials: 'include',
        }, false);
        
        this.responseData = await response.json();

        if (this.responseData) {
          // update the total voucher
          this.$emit('updateTotalVoucher', this.responseData.totalCount);
          this.$refs.uploadInfoModal.show();
        }

        this.$store.dispatch("alerts/addSuccess", `Het bestand is geupload.`);
        this.resetForm();
      } catch (e) {
        this.$store.dispatch(
          "alerts/addError",
          "Er is iets fout gegaan tijdens het uploaden"
        );
      } finally {
        this.isLoading = false;
      }
    },
    closeModal() {
      this.$refs.uploadInfoModal.hide();
    },
    onCloseModal() {
      this.responseData = {};
    },
  },
  computed: {
    containsFile() {
      return !!this.selectedCsv;
    },
  },
  components: {
    field,
    modal,
  },
};
</script>

<style lang="scss">
input[type="file"] {
  justify-self: center;
}
</style>
