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

export default {
  name: "PropertyField",
  props: ['model', 'values'],
  data() {
    return {
      widget_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>
  <div v-if="values.length===0" class="form-group cols">
    <div class="col-3 pl-2">
      <label class="form-label">{{ model.name }}</label>
    </div>
    <div class="col-9 pr-2">
      <button type="button" class="btn" @click="addValue">
        <i class="icon icon-plus"></i>Add
      </button>
    </div>
  </div>

  <div v-if="values.length>0" class="form-group cols" v-for="(value, vi) in values" :key="vi">
    <div class="col-3 pl-2">
      <label class="form-label" :for="widget_id" v-if="vi===0">{{ model.name }}</label>
    </div>
    <div class="col-9 pr-2">
      <string-value :ref="setFieldRef" :value="value" :id="vi === 0 ? widget_id : null" v-if="model.data_type==='String'"></string-value>
      <integer-value :ref="setFieldRef" :value="value" :id="vi === 0 ? widget_id : null" v-if="model.data_type==='Integer'"></integer-value>
      <decimal-value :ref="setFieldRef" :value="value" :id="vi === 0 ? widget_id : null" v-if="model.data_type==='Decimal'"></decimal-value>
      <boolean-value :ref="setFieldRef" :value="value" :id="vi === 0 ? widget_id : null" v-if="model.data_type==='Boolean'"></boolean-value>
      <button type="button" class="btn btn-delete ml-1" @click="removeValue(vi)" v-if="values.length > 1 || model.optional">
        <i class="icon icon-cross"></i>Remove
      </button>
    </div>
  </div>

  <div v-if="values.length>0 && model.multiple" class="form-group cols">
    <div class="col-3 pl-2"></div>
    <div class="col-9 pr-2">
      <button type="button" class="btn" @click="addValue">
        <i class="icon icon-plus"></i>Add
      </button>
    </div>
  </div>
</template>
