<template>
    <v-text-field
      :value="data"
      :label="$t(label_field)"
      @change="update"
      :rules="rules"
      :disabled="readOnly"
      :type="type"
      :error="error"
      :error-messages="errorMessage"
    >
    </v-text-field>
</template>

<script lang="ts">
  import {computed, defineComponent, toRef, ref} from '@nuxtjs/composition-api'
  import {useRepositoryHelper} from "~/use/store/useRepository";
  import {Repository} from "@vuex-orm/core";
  import {Model} from "~/models/Model";

  export default defineComponent({
    props: {
      repository:{
        type: Object as () => Repository<Model>,
        required: true
      },
      entry:{
        type: Object,
        required: true
      },
      field:{
        type: String,
        required: true
      },
      label:{
        type: String,
        required: false
      },
      type:{
        type: String,
        required: false
      },
      rules:{
        type: Array,
        required: false
      },
      error:{
        type: Boolean,
        required: false
      },
      errorMessage:{
        type: String,
        required: false
      }
    },
    setup(props, {emit}){
      const {label, field, repository } = props
      const entry = toRef(props, 'entry')
      const label_field = label ? label : field;

      const data = computed(() => entry.value[field])
      const update = (newValue:string) => {
        useRepositoryHelper.updateStoreFromField(repository, entry.value, newValue, field)
        emit('update', newValue)
      }
      const readOnly = computed(() => useRepositoryHelper.getReadOnly(repository))

      return {
        label_field,
        data,
        update,
        readOnly
      }
    }
  })
</script>

<style>
  input:read-only{
    color: #666 !important;
  }
</style>
