<script>
import {objCopy, uniqueId} from "../utils";
import * as Vue from 'vue';

export default {
  name: "PropertyField",
  props: ['model', 'values'],
  data() {
    return {
      id: uniqueId(),
      fieldRefs: [],
    }
  },
  methods: {
    addValue(event) {
      this.values.push(objCopy(this.model.default));

      Vue.nextTick(() => {
        this.fieldRefs[this.values.length-1].focus();
      })
    },
    removeValue(vi) {
      this.values.splice(vi, 1);
    },
    setFieldRef(el) {
      if (el) {
        this.fieldRefs.push(el)
      }
    },
  },
  beforeUpdate() {
    this.fieldRefs = []
  }
}
</script>

<template>
  <tr v-if="values.length===0">
    <th @click="addValue">{{model.name}}</th>
    <td>
      <a href="#" @click="addValue">Add</a>
    </td>
  </tr>
  <tr v-else v-for="(value, vi) in values" :key="vi">
    <th :rowspan="values.length + model.multiple" v-if="vi == 0"><label :for="id">{{model.name}}</label></th>
    <td>
      <string-value  :ref="setFieldRef" :value="value" :id="vi===0?id:null" v-if="model.data_type==='String'"></string-value>
      <integer-value :ref="setFieldRef" :value="value" :id="vi===0?id:null" v-if="model.data_type==='Integer'"></integer-value>
      <decimal-value :ref="setFieldRef" :value="value" :id="vi===0?id:null" v-if="model.data_type==='Decimal'"></decimal-value>
      <boolean-value :ref="setFieldRef" :value="value" :id="vi===0?id:null" v-if="model.data_type==='Boolean'"></boolean-value>
      <a href="#" @click="removeValue(vi)" v-if="vi > 0 || model.optional" style="margin-left:5px">X</a>
    </td>
  </tr>
  <tr v-if="values.length > 0 && model.multiple">
    <td>
      <a href="#" @click="addValue">Add</a>
    </td>
  </tr>
</template>
