<script>
import Vue from 'vue';

export default {
  name: 'validator-group-base',
  docs: `Voeg <code>
      import validatorGroupBase from '@nlo/cms-components/tools/validator-group-base.vue';
      extends: validatorGroupBase</code> toe aan je component,
    en je krijgt een <code>isValid</code> computed property die aangeeft of alle validators binnen je component valide zijn.`,
  data() {
    return {
      validators: [],
    };
  },
  beforeCreate() {
    this.eventBus = new Vue();

    this.eventBus.$on('validator-created', validator => {
      this.validators.push(validator);

      // this validator-group-base can be nested in another validator-group-base, so bubble the event further
      if (this.parentEventBus) {
        this.parentEventBus.$emit('validator-created', validator);
      }
    });

    this.eventBus.$on('validator-removed', validator => {
      this.validators.splice(this.validators.indexOf(validator), 1);

      // this validator-group-base can be nested in another validator-group-base, so bubble the event further
      if (this.parentEventBus) {
        this.parentEventBus.$emit('validator-removed', validator);
      }
    });
  },
  computed: {
    parentEventBus () {
      let target = this.$parent;
      while (target && !target.eventBus) {
        target = target.$parent;
      }

      return target ? target.eventBus : null;
    },
    isValid() {
      return this.validators.every(validator => validator.test);
    },
  },
};
</script>
