<template>
  <button class="btn btn-primary" :disabled="disabled || (validatorGroup && !validatorGroup.isValid) || actionRunning" @click="performAction" accesskey="S" title="Alt + S">
    <span v-if="!validatorGroup"><code>submit</code> needs to be used inside <code>validator-group</code>!</span>
    <slot>Versturen</slot>
  </button>
</template>

<script>
import { ValidatorMixin } from './validator-mixin.js';

export default {
  docs: `Submit button. Gebruiken binnen een <code>validator-group</code>. Wordt gedisabled als er validatie-errors zijn.`,
  mixins: [ValidatorMixin],
  props: {
    action: {
      type: Function,
      required: true
    },
    disabled: {
      type: Boolean
    }
  },
  data() {
    return {
      validatorGroup: null,
      actionRunning: false
    }
  },
  created() {
    this.getAndSetValidatorGroup();
  },
  methods: {
    getAndSetValidatorGroup() {
      // can only be done by events, because <validator-group> doesn't need to be the parent of this <submit>
      this.validatorEventBus.$emit('needs-validator-group', vg => this.validatorGroup = vg);
    },
    performAction() {
      var promise = this.action();
      if (!promise || !promise.then) {
        console.warn('The action function of a submit button should return a Promise.');
        return;
      }
      this.actionRunning = true;
      promise.then(
        () => this.actionRunning = false,
        () => this.actionRunning = false
      );
    }
  }
}
</script>
