<template>
  <div>
    <button type="button" v-for="(choice, index) in schema.oneOf" class="btn btn-outline-secondary mr-1 mb-1" @click="create(choice)" :key="index">
      <span class="icon-plus"></span> {{choice.title}}
    </button>

    <button type="button" class="btn btn-outline-secondary" @click="create(schema)" v-if="!schema.oneOf || !schema.oneOf.length">
      <span class="icon-plus"></span> {{schema.title}}
    </button>
  </div>
</template>

<script>
import { initialValue } from './schema-scripts.js';
import { ValueSyncMixin } from '../shared/value-sync-mixin.js';

export default {
  name: 'schema-add-buttons',
  docs: `Genereert buttons om een component toe te voegen.`,
  mixins: [ValueSyncMixin],
  props: {
    hasList: {
      type: Boolean,
      default: false,
    },
    value: {
      required: true,
    },
    schema: {
      type: Object,
      required: true,
      docs: `Schema voor het component dat moet worden toegevoegd.`,
      demoValue: () => ({ oneOf : [{ type: 'number', title: 'Nummer' }, { type: 'string', title: 'String' }] }),
    },
  },
  methods: {
    create(choice) {
      const value = initialValue(
        this.schema.type == 'object'
          ? { type: 'object', properties: { ...this.schema.properties, ...(choice ? choice.properties : {}) } }
          : choice
      );

      // set 'isNew' prop, so we are be able to show it in an open state in 'schema-page-component', 'isNew' is not saved
      if (this.schema.type == 'object') {
        value.isNew = true;
      }

      if (this.hasList) {
        // when there isn't set an initial value to a C# List<>, it is null
        this.valueCopy ? this.valueCopy.push(value) : this.valueCopy = [value];
      } else {
        this.valueCopy = value;
      }
    },
  },
};
</script>
