<template>
  <div>
    <input v-if="isLoading" class="form-control" disabled placeholder="Laden..." />
    <div class="text-danger col-form-label" v-else-if="!canRead(crudStoreName)">Je hebt geen rechten om dit veld te lezen.</div>
    <relation-picker
      v-else-if="!hasItemsError"
      v-model="valueCopy"
      :required="schema.required"
      :readonly="!!schema.isReadOnly"
      :multi="schema.type === 'array'"
      :display-component="displayComponent"
      :module="crudStoreName"
      :placeholder="schema.placeholder"
    ></relation-picker>
    <div class="text-danger col-form-label" v-else>Er ging iets mis bij het ophalen van de waardes voor dit veld.</div>
    <schema-validator :value="valueCopy" :schema="schema"></schema-validator>
  </div>
</template>

<script>
import { ValueSyncMixin } from '../shared/value-sync-mixin.js';
import formElements from '../shared/form/all';
import schemaValidator from './schema-validator.vue';
import { mapGetters, mapState } from 'vuex';
import CrudHelpers from './../crud/crud-helpers';

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
    }
  },
  data() {
    return {
      crudStoreName: CrudHelpers.getStoreNameForReference(this.reference)
    };
  },
  computed: {
    ...mapGetters('permissions', ['canRead']),
    ...mapState({
      // this syntax is needed to get 'this' working in mapState
      isLoading(state) {
        return !state[this.crudStoreName].schema;
      },
      hasItemsError(state) {
        return state[this.crudStoreName].hasItemsError;
      }
    })
  },
  components: {
    ...formElements,
    schemaValidator
  }
};
</script>
