<template>
  <v-col
    cols="12"
    sm="6"
  >
    <v-text-field
      v-model="data[field]"
      @change="update()"
      color="purple darken-2"
      :rules="rules"
      required
    ></v-text-field>
  </v-col>
</template>

<script lang="ts">
  import {unref, defineComponent, ref, watch, onUnmounted} from '@vue/composition-api'
  import {Repository} from "@vuex-orm/core";
  import {cloneAndFlatten, cloneAndNest} from "~/services/objectProperties";

  export default defineComponent({
    props: {
      repository:{
        type: Object as () => Repository,
        required: true
      },
      field:{
        type: String,
        required: true
      },
      rules:{
        type: Array,
        required: false
      }
    },
    setup({repository, field}, {root}){
      const data = ref({})

      const update = () => {
        repository.update(cloneAndNest(unref(data)))
      }

      /* const unwatch = watch(
        () => root.$store.state.entities.people.data,
        (state, prevState) => {
         unref(data)[field] = state
        }
      )
      onUnmounted(() => {
        unwatch()
      }) */

      return {
        data,
        update
      }
    },
    async fetch() {
      const data = await this.repository.find(parseInt(this.$route.params.id));
      this.data = cloneAndFlatten(data);
    }
  })
</script>

<style scoped>
</style>
