<template>
  <div>
    <input v-if="isLoading" class="form-control" disabled placeholder="Laden...">
    <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 { handleFetch } from '../../api/helpers'
import { ValueSyncMixin } from '../value-sync-mixin.js';
import * as formElements from '../form/all.js';
import schemaValidator from '../../schema/schema-validator.vue';

export default {
  docs: `Een relatie-picker op basis van het JSON schema en een externe referentie uri.`,
  mixins: [ValueSyncMixin],
  props: {
    value: {
      required: true,
      demoValue: () => [],
    },
    schema: {
      type: Object,
      required: true,
      demoValue: () => ({
        type: 'array',
      }),
    },
    reference: {
      type: String,
      required: true,
      demoValue: '/product',
    },
    displayComponent: {
      required: false,
    },
  },
  data() {
    return {
      isLoading: false,
      hasItemsError: false,
      items: [],
      fields: ['id', 'displayName'],
      displayField: 'displayName'
    };
  },
  async beforeMount() {
    try {
      const response = await handleFetch(this.reference);
      const result = await response.json();

      if (!(result instanceof Array) || result.length == 0) {
        throw new Error("External reference is not an array, or does not contain any items");
      }

      const displayField = this.getDisplayName(result[0]);
      this.items = result.map(item => { return { id: item[this.externalReferenceId], displayName: item[displayField] }; })
    } catch(e) {
      this.hasItemsError = true;
      this.$store.dispatch('alerts/addError', `Er ging helaas wat mis bij het ophalen van ${this.schema.title}.`);
      console.error(e.message);
    }
  },
  methods: {
    getDisplayName(item) {
      var entries = Object.entries(item);
      var filteredEntries = entries.filter(entry => typeof(entry[1]) === 'string' && entry[0] != "$type" && entry[0] != this.externalReferenceId);
      return filteredEntries.length > 0 ? `${filteredEntries[0][0]}` : this.externalReferenceId;
    }
  },
  computed: {
    externalReferenceId() {
      return this.schema.externalReferenceId != null ? this.schema.externalReferenceId : 'id';
    }
  },
  components: {
    ...formElements,
    schemaValidator,
  },
};
</script>
