<template>
  <div class="card">
    <header class="card-header">
      <h5 class="mb-0">Activeer Sweepstake</h5>
    </header>
    <div class="card-body">
      <form @submit.prevent="submit">
        <input type="hidden" name="sweepstakeId" :value="this.sweepstakeId">

        <field label="Sweepstake activeren" info="Zodra de sweepstake geactiveerd is, kunnen aantallen en volgorde van de Prijzen niet meer worden aangepast!" no-focus>
          <button
            :disabled="isActivating"
            v-text="isActivating ? 'Bezig met activeren...' : 'Activeer'"
            class="btn btn-primary"
          ></button>
        </field>
      </form>
    </div>
  </div>
</template>

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

export default {
  props: {
    sweepstakeId: {
      type: String,
      required: true,
    },
    urlPart: {
      type: String,
      required: true,
    },
    value: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isActivating: false,
    };
  },
  methods: {
    async submit(e) {
      this.isActivating = true;
      try {
        // Activate on the server and then notify the store that properties have changed.
        // That notification is necessary to let the list of sweepstakes display a checkmark in the Active column when returning to the list.
        const sweepstake = await this.postForm(e.target);
        this.$store.dispatch('sweepstake/fetchCrudItems');

        // Notify user and update the current editor GUI.
        this.$store.dispatch('alerts/addSuccess', `Geactiveerd`);
        this.$emit('input', { isActive : sweepstake.isActive, hashPrizeDefinitions: sweepstake.hashPrizeDefinitions });

      } catch(e) {
        this.$store.dispatch('alerts/addError', 'Er is iets fout gegaan tijdens het activeren.');
      } finally {
        this.isActivating = false;
      }
    },
    async postForm(form) {
      const response = await handleFetch('/' + this.urlPart + '/activate', {
        method: 'post',
        body: new FormData(form),
        credentials: 'include',
      }, false);

      return await response.json();
    },
  },
  components: {
    field,
  },
};
</script>
