<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" :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>Er ging iets mis bij het ophalen van de waardes voor dit veld.</div>
    <schema-validator :value="valueCopy" :schema="schema"></schema-validator>
    <validator :test="!schema.required || !!valueCopy">Veld is verplicht</validator>

  </div>
</template>

<script>
import { ValueSyncMixin } from '../shared/value-sync-mixin.js';
import * as formElements from '../shared/form/all.js';
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),
      unsubscribe: null
    };
  },
  async beforeMount() {
    this.unsubscribe = await CrudHelpers.subscribeCrudData(this.crudStoreName);
  },
  beforeDestroy() {
    if (this.unsubscribe) {
      this.unsubscribe();
    }
  },
  computed: {
    ...mapGetters('permissions', [
      'canRead',
    ]),
    ...mapState({
      // this syntax is needed to get 'this' working in mapState
      isLoading (state) {
        return state[this.crudStoreName].loading;
      },
      items (state) {
        return state[this.crudStoreName].items;
      },
      fields (state) {
        return state[this.crudStoreName].overview.fields;
      },
      crudItemSchema (state) {
        return state[this.crudStoreName].schema;
      },
      hasItemsError (state) {
        return state[this.crudStoreName].hasItemsError;
      },
    }),
    displayField() {
      return CrudHelpers.getDisplayFieldForSchemaProperties(this.crudItemSchema && this.crudItemSchema.properties || undefined);
    },
  },
  components: {
    ...formElements,
    schemaValidator,
  },
};
</script>
