<template>
  <div>
    <validator v-if="schema.required" :test="exists(value)">
      {{ message('required', requiredMessage )}}
    </validator>
    <validator v-if="schema.minLength !== undefined" :test="value == null || (value.length >= schema.minLength && checkArrayValidity(value))">
      {{ message('minLength', 'De minimale lengte is ' + schema.minLength) }}
    </validator>
    <validator v-if="schema.maxLength !== undefined" :test="value == null || value.length <= schema.maxLength">
      {{ message('maxLength', 'De maximale lengte is ' + schema.maxLength) }}
    </validator>
    <validator v-if="schema.minimum !== undefined" :test="value == null || value >= schema.minimum">
      {{ message('minimum', 'De minimale waarde is ' + schema.minimum) }}
    </validator>
    <validator v-if="schema.maximum !== undefined" :test="value == null || value <= schema.maximum">
      {{ message('maximum', 'De maximale waarde is ' + schema.maximum) }}
    </validator>
    <validator v-if="schema.options !== undefined" :test="!value || isEnumSelected">
      {{ message('enum', 'Kies een waarde uit de lijst') }}
    </validator>
    <validator v-if="schema.pattern !== undefined" :test="value == null || regExpTest(value, schema.pattern)">
      {{ message('pattern', 'De waarde voldoet niet aan het vereiste patroon.') }}
    </validator>
  </div>
</template>

<script>
import * as formElements from '../shared/form/all.js';

export default {
  name: 'schema-validator',
  props: {
    value: {
      required: true,
    },
    schema: {
      type: Object,
      required: true,
    },
  },
  methods: {
    message(type, fallback) {
      return (this.schema.messages && this.schema.messages[type]) || fallback;
    },
    regExpTest(value, pattern) {
      return new RegExp(pattern).test(value);
    },
    exists(value) {
      return value !== null && value !== undefined && value !== '';
    },
    checkArrayValidity(value) {
      return !Array.isArray(value) || value.every(v => this.exists(v));
    }
  },
  computed: {
    isEnumSelected() {
      return !this.schema.options || this.schema.options.findIndex(option => {
        return option.key === this.value;
      }) > -1;
    },
    requiredMessage() {
      return `${this.schema.title || 'Veld'} is verplicht`;
    }
  },
  components: {
    ...formElements,
  },
};
</script>
