<template>
  <div>
    <validator v-if="schema.required" :test="value !== null && value !== undefined && value !== ''">
      {{ message('required', 'Kun je dit veld nog invullen?') }}
    </validator>

    <!-- Only check following validators if required value is provided. So we don't show double messages when there is no value-->
    <slot v-if="!!value">
      <validator v-if="schema.minLength !== undefined" :test="value.length >= schema.minLength">
        {{ message('minLength', 'De minimale lengte is ' + schema.minLength) }}
      </validator>
      <validator v-if="schema.maxLength !== undefined" :test="value.length <= schema.maxLength">
        {{ message('maxLength', 'De maximale lengte is ' + schema.maxLength) }}
      </validator>
      <validator v-if="schema.minimum !== undefined" :test="value >= schema.minimum">
        {{ message('minimum', 'De minimale waarde is ' + schema.minimum) }}
      </validator>
      <validator v-if="schema.maximum !== undefined" :test="value <= schema.maximum">
        {{ message('maximum', 'De maximale waarde is ' + schema.maximum) }}
      </validator>
      <validator v-if="schema.options !== undefined" :test="isEnumSelected">
        {{ message('enum', 'Kies een waarde uit de lijst') }}
      </validator>
      <validator v-if="schema.pattern !== undefined" :test="regExpTest(value, schema.pattern)">
        {{
          message(
            'pattern',
            'Check dit veld nog even. De ingevulde karakters voldoen niet aan het vereiste patroon van dit veld. Mogelijk geeft het i-tje meer uitleg.'
          )
        }}
      </validator>
    </slot>
  </div>
</template>

<script lang="ts">
import validator from '../shared/form/validator.vue';

import { Component, Prop, Vue } from 'vue-property-decorator';
import { SchemaProperty } from '../types/api';

@Component({
  components: {
    validator
  }
})
export default class SchemaValidator extends Vue {
  @Prop(Object) readonly schema!: SchemaProperty;
  @Prop({ required: true }) readonly value!: string;

  message(type, fallback) {
    return (this.schema.messages && this.schema.messages[type]) || fallback;
  }

  regExpTest(value, pattern) {
    return new RegExp(pattern).test(value);
  }

  get isEnumSelected() {
    return (
      !this.schema.options ||
      this.schema.options.findIndex((option) => {
        return option.key === this.value;
      }) > -1
    );
  }
}
</script>
