<template>
  <div>

    <input v-if="isLoading" class="form-control" disabled placeholder="Laden...">
    <relation-picker v-else-if="!crudStore.state.fetchItemsError" v-model="valueCopy" :source="items" :fields="fields" :display-field="displayField" :required="schema.required" :readonly="!!schema.isReadOnly" :multi="schema.type == 'array'" :display-component="displayComponent"></relation-picker>
    <div class="text-danger col-form-label" v-else="crudStore.state.fetchItemsError">Je hebt geen rechten om dit veld te lezen.</div>
    <schema-validator :value="valueCopy" :schema="schema"></schema-validator>
    <validator :test="!schema.required || !!valueCopy">Veld is verplicht</validator>

  </div>
</template>

<script>
import { crudStores } from '../tools/crud-stores.js';
import { ValueSyncMixin } from '../shared/value-sync-mixin.js';
import * as formElements from '../shared/form/all.js';
import schemaValidator from './schema-validator.vue';

export default {
  docs: `Een relatie-picker op basis van het JSON schema en een JSON schema referentie uri.`,
  mixins: [ValueSyncMixin],
  props: {
    value: {
      required: true,
      demoValue: () => []
    },
    schema: {
      type: Object,
      required: true,
      demoValue: () => ({
        type: 'array'
      })
    },
    reference: {
      type: String,
      required: true,
      demoValue: '/items/product/schema'
    },
    displayComponent: {
      required: false
    }
  },
  computed: {
    crudStore() {
      return crudStores.getStoreBySchemaRef(this.reference);
    },
    items() {
      return this.crudStore.items;
    },
    displayField() {
      return this.crudStore.displayField;
    },
    isLoading() {
      return this.crudStore.isLoading
    },
    fields() {
      return this.crudStore.fields;
    }
  },
  components: {
    ...formElements,
    schemaValidator
  }
}
</script>
